Jason Varga
Jason Varga

Reputation: 1959

Merge and rearrange nested key/values

I have an array like this:

array(
  0 => array(
    'name' => 'colors',
    'options' => array(
      array('name'=>'red', 'price'=>'2'),
      array('name'=>'blue', 'price'=>'3')
    )
  ),
  1 => array(
    'name' => 'sizes',
    'options' => array(
      array('name'=>'small', 'price'=>'5'),
      array('name'=>'large', 'price'=>'10')
    )
  ),
);

I want to merge all of the nested options arrays' name/prices into one, so it'll be like this:

array(
  'red' => '2',
  'blue' => '3',
  'small' => '5',
  'large' => '10'
);

I have a feeling this is very simple, but anything I try seems too convoluted. Any help would be appreciated.

...and yes, I just posted almost the same question not too long ago. This is a bit different, and what I meant to ask in the first place - oops, sorry.

Upvotes: 0

Views: 56

Answers (4)

varta.convonix
varta.convonix

Reputation: 26

Iterate through "options" in the nested array and create a new array :

<?php
$arr = array(
  0 => array(
    'name' => 'colors',
    'options' => array(
      array('name'=>'red', 'price'=>'2'),
      array('name'=>'blue', 'price'=>'3')
    )
  ),
  1 => array(
    'name' => 'sizes',
    'options' => array(
      array('name'=>'small', 'price'=>'5'),
      array('name'=>'large', 'price'=>'10')
    )
  ),
);

$group = array();
foreach($arr as $a){
    foreach($a['options'] as $op){        
        $group[$op['name']] = $op['price'];        
}
}

print_r($group);

?>

Upvotes: 0

jerdiggity
jerdiggity

Reputation: 3665

Here's another way, assuming the array has been assigned to the variable $a:

<?php
for ($i = 0; $i < count($a); $i++) {
  $key = $a[$i]['name'];
  $options = $a[$i]['options'];
  for ($j = 0; $j <  count($options); $j++) {
    $optkey = $options[$j]['name'];
    $prices[$optkey] = $options[$j]['price'];
  }
}

print_r($prices);

Upvotes: 0

Iłya Bursov
Iłya Bursov

Reputation: 24156

You need to decide how you will handle collisions, anyway here is same which will give you right direction:

$newArray = array();
foreach ($array as $i => $item)
    foreach ($item['options'] as $j => $option)
        $newArray[$option['name']] = $option['price'];

Upvotes: 1

kero
kero

Reputation: 10638

I'm not sure if this can be done with internal methods such as array_merge(), array_combine(), etc since your structure seems quite special. But how about iterating over the array and building a new one yourself?

function customRearrange($arr) {
    $result = array();
    foreach ($arr as $group) {
        foreach ($group['options'] as $option) {
            // prevents values from being overwritten, uncomment if unwanted
            if (!array_key_exists($option['name'], $result))
                $result[ $option['name'] ] = $option['price'];
        }
    }
    return $result;
}

Upvotes: 1

Related Questions