user3733648
user3733648

Reputation: 1333

converting nested arrays into associative array

My array look like. I am trying to convert it to single associative array, which will contain all the nesteds keys of nested arrays.

array(
    (int) 0 => array(
        'Size' => array(
            'id' => '12',
            'name' => 'Mini'
        ),
        'Price' => array(
            'price' => '4.35'
        )
    ),
    (int) 1 => array(
        'Size' => array(
            'id' => '13',
            'name' => 'Medium'
        ),
        'Price' => array(
            'price' => '6.15'
        )
    ),
    (int) 2 => array(
        'Size' => array(
            'id' => '15',
            'name' => 'Maxi'
        ),
        'Price' => array(
            'price' => '11.75'
        )
    )
)

Is there any function available which takes this array created a new something like

array(
        (int) 0 => array(
                'id' => '12',
                'name' => 'Mini'
                'price' => '4.35'
            ),
           ...,
           ...
        )

Upvotes: 0

Views: 106

Answers (5)

Neo
Neo

Reputation: 407

Try this code

$test = array(
(int) 0 => array(
    'Size' => array(
        'id' => '12',
        'name' => 'Mini'
    ),
    'Price' => array(
        'price' => '4.35'
    )
),
(int) 1 => array(
    'Size' => array(
        'id' => '13',
        'name' => 'Medium'
    ),
    'Price' => array(
        'price' => '6.15'
    )
),
(int) 2 => array(
    'Size' => array(
        'id' => '15',
        'name' => 'Maxi'
    ),
    'Price' => array(
        'price' => '11.75'
    )
)
);
$result = array();
$i=0;
foreach ($test as $temp){

$result[$i] = array(
        'id' => $temp['Size']['id'],
        'name' => $temp['Size']['name'],
        'price' => $temp['Price']['price']
    );

$i++;
}
echo "<pre/>";
print_r($result);

Upvotes: 1

voodoo417
voodoo417

Reputation: 12111

$new_array = array();
foreach($array as $key=>$data) {
   $new_array[$key] = array_reduce( $data,'array_merge',array());
}

echo '<pre>';
print_r($new_array);
echo '</pre>';

http://codepad.viper-7.com/vclE9v

Upvotes: 1

S.Pols
S.Pols

Reputation: 3434

For this specific array you could use something like this:

$newArray = array();
foreach($array as $key => $arrayItem)
{
    $newArray[$key]['id'] = $arrayItem['Size']['id'];
    $newArray[$key]['name'] = $arrayItem['Size']['name'];
    $newArray[$key]['price'] = $arrayItem['Price']['price'];
}

Upvotes: 1

Kevin
Kevin

Reputation: 41893

You could use call_user_func_array() in this case:

$new_array = array();
foreach($array as $values) {
    $new_array[] = call_user_func_array('array_merge', $values);
}

echo '<pre>';
print_r($new_array);

Sample Output

Upvotes: 2

Buri
Buri

Reputation: 71

$result = array_map($source_array, function ($item){ return array_flatten($item); });

Upvotes: 0

Related Questions