基于PHP数组的初始键排序?

时间:2022-03-29 21:31:43

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.

我想将包含许多键和值的初始数组(s)排序为数组(s),按特定键排序,并根据键在单个数组中对该键的所有值进行排序。

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.

我希望这说得通。我发现向你展示一个例子比较容易,就像反对描述它一样。

4 个解决方案

#1


2  

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

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

var_dump($after);

#2


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

现场演示

#3


0  

Maybe something like:

也许类似:

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

#4


0  

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

This should work :)

这应该工作:)

#1


2  

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

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

var_dump($after);

#2


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

现场演示

#3


0  

Maybe something like:

也许类似:

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

#4


0  

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

This should work :)

这应该工作:)