質問

I have the following array of data:

$data = array(
 0 => array(
   'firstname' => 'John',
   'lastname' => 'Doe'
 ),
 1 => array(
   'firstname' => 'Foo',
   'lastname' => 'Bar'
 )
)

And Id like to manipulate it to end up with this array:

$finalData = array(
 'firstname' => array('John','Foo'),
 'lastname' => array('Doe','Bar')
)

How do I accomplish this using PHP? Id love to learn about the PHP array methods if one can be used in this scenario.

Thanks!

正しい解決策はありません

他のヒント

This is too specialized for functions like array_map without shooting yourself in the foot. But you can easily do it with a foreach loop:

$finalData = array();
foreach ($data as $person) {
    $finalData['firstname'][] = $person['firstname'];
    $finalData['lastname'][] = $person['lastname'];
}

You will have to loop through $data to gather first names and last names separately. Unfortunately there is no standard php function that performs "array pluck".

Well, I don't think that something like that exist, but I think You should read docs on array functions

If You don't find anything, make something your own (probably with with array_map), and please answer your own question.

This gives what you want;

$new_data = array();
foreach ($data as $d) {
    $keys = array_keys($d);
    foreach ($keys as $k) {
        $new_data[$k][] = $d[$k];
    }
}
print_r($new_data);

Result;

Array
(
    [firstname] => Array
        (
            [0] => John
            [1] => Foo
        )

    [lastname] => Array
        (
            [0] => Doe
            [1] => Bar
        )

)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top