2

I have foreach loop like:

foreach($attributes as $key => $value)
{
     $option[] =["$value->name"=>"$value->value"]; //it is like ["color"=>"red"]
}

I want to merge $option[0], $option[1] and so on.... How to merge that ?

I tried:

for($i=1;$i<$count;$i++)
{   
        $option = array_merge($option[0],$option[$i]);
}
David Coder
  • 1,138
  • 2
  • 14
  • 48
  • 4
    What about this: `$option[$value->name] = $value->value;` in foreach? This array will contain all key/value pairs of options. – user4035 Mar 22 '16 at 10:15
  • $value->name is key and $value->value is value of array – David Coder Mar 22 '16 at 10:18
  • 1
    If that does not fulfill your needs, give an example for clarification (in the question). – syck Mar 22 '16 at 10:19
  • @DeepParekh I gave you a preliminary answer. Let me know, how it worked. – user4035 Mar 22 '16 at 10:21
  • 1
    user4035 is correct: if you want it then you will directly have an array where, for instance, `$option['color]` is `'red'`, Or, if you want to follow your approach, you can either declare a new array (`$opt = []; foreach ($options as $value) $opt = array_merge($opt, $value);`) or put the value in `$option[0]` instead of `$option`; or you can read [these answers](http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php) which have ways of flattening an array – frarugi87 Mar 22 '16 at 10:22

3 Answers3

3

If you want a merged version, try this (you need only 1 loop):

$merged_options = array();
foreach($attributes as $key => $value)
{
     $option[] =["$value->name" => "$value->value"];
     $merged_options[$value->name] = $value->value;
}
user4035
  • 22,508
  • 11
  • 59
  • 94
3

This code should hopefully loop through each of your current arrays and reconstruct it to a multi-dimensional array.

foreach($attr as $k=>$v):
    $temp = array();
    $i = 0;
    while(count($k) != $i):
        array_push($temp, $k[$i] => $v[$i]);
        $i++;
    endwhile;
    array_push($attr, $temp);
endforeach;

Hope it helped.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
2

Why not you use something like this:

foreach($attributes as $key => $value)
{
     $option[$value->name] =$value->value;
}
Anand Singh
  • 2,343
  • 1
  • 22
  • 34