i have an array:
Array
(
[47] => Array
(
[name] => 3543 good
[price] => 100.0000
[image] => data/hp_1.jpg
[discount] =>
[stock_status] =>
[weight_class] => kg
)
[28] => Array
(
[name] => HTC Touch HD
[price] => 100.0000
[image] => data/htc_touch_hd_1.jpg
[discount] =>
[stock_status] =>
[weight_class] => g
)
[41] => Array
(
[name] => iMac
[price] => 100.0000
[image] => data/imac_1.jpg
[discount] =>
[stock_status] =>
[weight_class] => kg
)
[40] => Array
(
[name] => iPhone
[price] => 101.0000
[image] => data/iphone_1.jpg
[discount] =>
[stock_status] =>
[weight_class] => kg
)
)
i need the sub array key (47 ,28 etc) as it is my product id
I'm running a foreach loop to get the details and assigning to a new array e.g. 'name' => $result['name']
but can't figure out how to target the product id.
You can assign the key to a variable in your foreach loop:
foreach($array as $id => $result) {
$item = array('name' => $result['name'], 'id' => $id);
}
Add the key variable to your foreach
loop, like so:
foreach( $array as $product_id => $result)
echo $product_id . ' costs ' . $result['price'] . "
";
Iterate over it as a associative array with a key value pair.
foreach($array as $key=>$value) {
echo $key; // this is what you need, if I got you right
}
foreach
allows you to iterate over not just the values but also the keys in this way:
foreach($items as $key => $value)
{
...
}
In your case it would look like:
foreach($results as $id => $result)
{
$item = array('name' => $result['name'], 'id' => $id, ...);
}