将嵌套数组转换为关联数组

时间:2014-12-03 13:59:26

标签: php arrays multidimensional-array

我的阵列看起来像。我试图将它转换为单个关联数组,它将包含所有 嵌套数组的嵌套键。

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

是否有任何可用的功能可以使这个数组创建一个像

这样的新东西
array(
        (int) 0 => array(
                'id' => '12',
                'name' => 'Mini'
                'price' => '4.35'
            ),
           ...,
           ...
        )

5 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用call_user_func_array()

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

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

Sample Output

答案 1 :(得分:1)

对于这个特定的数组,您可以使用以下内容:

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

答案 2 :(得分: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

答案 3 :(得分:1)

试试此代码

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

答案 4 :(得分:0)

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