0

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'
            ),
           ...,
           ...
        )

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

1
$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

Comments

1

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'];
}

Comments

1

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);

Comments

0

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

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.