Vincent
Vincent

Reputation: 852

multiple array to a single array php

is it possible in php to change this array

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

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

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

        )

)

to this kind of array . in which their index names are same.

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

Upvotes: 0

Views: 60

Answers (1)

Giacomo1968
Giacomo1968

Reputation: 26066

Just use a foreach loop like this:

// 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>';

And the final results are:

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

Upvotes: 1

Related Questions