TMH
TMH

Reputation: 6246

Transpose an indexed array of associative arrays

I have an array of date like this

Array
(
    [0] => Array
        (
            [imageName] => WNgrRdqZ
            [alt] => alt text
        )

    [1] => Array
        (
            [imageName] => xoPS0udB
            [alt] => Alt
        )

)

And I'm wanted to format it so I get one array of imageNames, and one array of alt. I can do this simply with a foreach loop, but I'm curious if there's a build in PHP function I could use instead of rewriting something else. I've not found anything useful yet in the PHP manual.

EDIT: It could also be split into 1 array with 2 sub arrays, e.g.

Array
    (
        ['imageName'] => Array(..),
        ['alt'] => Array(...)
    )

Upvotes: 0

Views: 95

Answers (3)

Karthick Kumar
Karthick Kumar

Reputation: 2361

please review this code

<?php
$arraystest = array(0 => array('imageName' => 'WNgrRdqZ', 'alt' => 'alt text'), 1 => array('imageName' => 'xoPS0udB', 'alt' => 'Alt'));
$i = 0;
$newarray = array();
foreach ($arraystest as $item) {
    $newarray['imagename'][$i] = $item['imageName'];
    $newarray['alt'][$i] = $item['alt'];
    $i++;
}

print_r($newarray);
exit;
?>

Upvotes: 0

Marecky
Marecky

Reputation: 2096

You can use array_reduce:

<?php

$data = array
(
    array
    (
        'imageName' => 'WNgrRdqZ',
        'alt' => 'alt text'
    ),

    array
    (
        'imageName' => 'xoPS0udB',
        'alt' => 'Alt'
    )
);


$reduced = array_reduce($data,function($carry, $item){
    $carry['imageName'][] = $item['imageName'];
    $carry['alt'][] = $item['alt'];
    return $carry;
},array());

print_r($reduced);

Working example https://ideone.com/48JXvL

Upvotes: 0

Sudec
Sudec

Reputation: 124

You can use array_column():

$imageName = array_column($Array, 'imageName');
$alt = array_column($Array, 'alt');

Upvotes: 3

Related Questions