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]);
}
5
  • 4
    What about this: $option[$value->name] = $value->value; in foreach? This array will contain all key/value pairs of options. Commented Mar 22, 2016 at 10:15
  • $value->name is key and $value->value is value of array Commented Mar 22, 2016 at 10:18
  • 1
    If that does not fulfill your needs, give an example for clarification (in the question). Commented Mar 22, 2016 at 10:19
  • @DeepParekh I gave you a preliminary answer. Let me know, how it worked. Commented Mar 22, 2016 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 which have ways of flattening an array Commented Mar 22, 2016 at 10:22

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

Why not you use something like this:

foreach($attributes as $key => $value)
{
     $option[$value->name] =$value->value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.