多个数组到单个数组php

时间:2014-06-17 16:34:28

标签: php arrays

是否可以在php中更改此数组

Array
(
    [0] => Array
        (
            [image_name] => image1
        )

    [1] => Array
        (
            [image_name] => image2
        )

    [2] => Array
        (
            [image_name] => image3

        )

)

到这种阵列。其索引名称相同。

Array
(
    [image_name1] => image1
    [image_name2] => image2
    [image_name3] => image3 
)

1 个答案:

答案 0 :(得分:1)

只需使用foreach这样的循环:

// Set a test array.
$test_array = array();
$test_array[] = array('image_name_1' => 'image1');
$test_array[] = array('image_name_2' => 'image2');
$test_array[] = array('image_name_3' => 'image3');

// Roll through the array & set a new array.
$new_array = array();
foreach($test_array as $parent_key => $parent_value) {
  foreach($parent_value as $child_key => $child_value) {
    $new_array[$child_key] = $child_value;
  }
}

// Dump the output for debugging.
echo '<pre>';
print_r($new_array);
echo '</pre>';

最终的结果是:

Array
(
    [image_name_1] => image1
    [image_name_2] => image2
    [image_name_3] => image3
)