0

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 
)
5
  • 2
    The way you imagined it, is not possible. An array can have a single value for a single key. It cannot contain the image_name key multiple times. What would $array['image_name'] return? Commented Jun 17, 2014 at 16:36
  • php.net//manual/en/function.array-merge.php Commented Jun 17, 2014 at 16:36
  • You could make $arary['image_name'] an array of values, but the way you show in your example is not possible. Commented Jun 17, 2014 at 16:37
  • $flattened = array_column($oldArray, 'image_name'); as a quick way of flattening that array for PHP >= 5.5; but you must still have unique keys for the index Commented Jun 17, 2014 at 16:38
  • 2
    What's wrong with a simple enumerated index? Why do you need an associative index with incrementing numbers? Commented Jun 17, 2014 at 16:41

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

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.