snh_nl
snh_nl

Reputation: 2955

PHP foreach /w key+value pairs over part of multi dimensional array

I am trying to access data from a multidimensional array. Array $o contains arrays of with the key: product_id. The child array 'data' contains key => value pairs (or at least I think it does). The problems is that when I try to access the data later on: nothing is working.

Question: How can I access this data as expected in a key => value pair method that works (like foreach($o[$_product_id]['data'] as $_attr => $_value))

Original data

$_product_id=1;
$h = array('header1','header2','header3');
$line= array(1,2,3);
$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));

I var_dumped $o[$_product_id]['data'] and I can see the data is there

$data =
array (
  'header1' => 1,
  'header2' => 2,
  'header3' => 3,
);

Help appreciated

=======================

Loading data original method

$o[$_product_id]['data'] = array_combine($h,array_map('trim', $line));

Loading data alternative method

foreach ($h as $_atr) {
  $o[$_product_id]['data'][$_atr] = trim(array_shift($line));
}

Accessing data: not working as expected

foreach($o[$_product_id]['data'] as $_attr => $_value)
  echo $_attr;
  echo $_value;

Upvotes: 0

Views: 28

Answers (1)

u_mulder
u_mulder

Reputation: 54841

Okay, your problem is that your code:

foreach($o[$_product_id]['data'] as $_attr => $_value)
  echo $_attr;
  echo $_value;

is equivalent to:

foreach($o[$_product_id]['data'] as $_attr => $_value) {
  echo $_attr;
}
echo $_value;

See? You iterate over array, but output only keys, and last value after the end.

And yes, this is the standard behaviour of a foreach without {} - after foreach definition only one line runs in a loop. All other lines are considered out of the loop. Yep, that's not like in python).

So the fix is simple - add {}:

foreach($o[$_product_id]['data'] as $_attr => $_value) {
  echo $_attr;
  echo $_value;
}

Upvotes: 1

Related Questions