2

I want to sort my initial array(s) that contain many keys and values inside, into array(s) sorted by a specific key, and all the values for that key in a single array based on the key.

So here's the array I have:

$Before = Array(Array("id" => 1, "name" => "Dogs"), 
                Array("id" => 2, "name" => "Lions"), 
                Array("id" => 3, "name" => "Tigers"));

And this is the array that I would like to end up with:

$After = Array("ids"   => Array(1, 2, 3), 
               "names" => Array("Dogs", "Lions", "Tigers"));

I hope that makes sense. I found it easier to show you an example, as oppose to describing it.

3
  • This looks more like a restructure than a sort Commented Jun 3, 2013 at 11:44
  • Yeah, wasn't exactly sure how to phrase it. Commented Jun 3, 2013 at 11:45
  • If you did need it sorted as well as restructured, could try using the code in example #3 of php.net/manual/en/function.array-multisort.php Commented Jun 3, 2013 at 11:48

4 Answers 4

2
$after = array(
    'ids'   => array(),
    'names' => array()
);

foreach($before as $row){
    $after['ids'][]   = $row['id'];
    $after['names'][] = $row['name'];
}

var_dump($after);
Sign up to request clarification or add additional context in comments.

Comments

2

You can use array_reduce

$After = array_reduce($Before, function ($a, $b) {
    $a['ids'][] = $b['id'];
    $a['names'][] = $b['name'];
    return $a;
});

Live DEMO

Comments

0

Maybe something like:

foreach ($input as $item) {
    foreach ($item as $field => $value) {
        $result[$field][] = $value;
    }
}
    var_dump($result);

Comments

0
$After = array();
foreach ($Before as $a) {
    $After['ids'][] = $a['id'];
    $After['names'][] = $a['name'];
}

This should work :)

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.