如何结合相同的键数组值?

时间:2019-09-26 10:32:19

标签: php arrays

所以我有这个从查询中得到的数组。当我print_r

时,数组看起来像这样
Array
(
    [0] => Array
        (
            [Name] => NAME 1
            [Last] => LastValue1
            [Bid] => 
            [Ask] => 
        )

    [1] => Array
        (
            [Name] => NAME 1
            [Last] => 
            [Bid] => BidValue1
            [Ask] => 
        )

    [2] => Array
        (
            [Name] => Name 2
            [Last] => LastValue2
            [Bid] => BidValue2
            [Ask] =>
        )
    [3] => Array
    (
        [Name] => NAME 1
        [Last] => 
        [Bid] => 
        [Ask] => AskValue1
    )
    [4] => Array
    (
        [Name] =>Name 2
        [Last] => 
        [Bid] => 
        [Ask] => AskValue2
    )

)

我想实现数组看起来像这样

Array
(
    [0] => Array
        (
            [Name] => NAME 1
            [Last] => LastValue1
            [Bid] => BidValue1
            [Ask] => AskValue1
        )

    [2] => Array
        (
            [Name] => Name 2
            [Last] => LastValue2
            [Bid] => BidValue2
            [Ask] => AskValue2
        )

)

我尝试这种方式(从Google获取)

$result = array();
foreach ($newArray as $element) {
    $result[$element['Name']][] = $element;
}

echo "<pre>";print_r($result);

但是它没有显示我想要的结果。我该如何实现? 在此先感谢您,我的英语很抱歉

2 个答案:

答案 0 :(得分:0)

您可以在以下代码段中使用相同的代码

$result = [];
foreach ($newArray as $element) {
    foreach ($element as $key => $value) {
        // checking if value for key is already added to result array
        if ((!empty($result[$element['Name']]) && !array_key_exists($key, $result[$element['Name']])) || empty($result[$element['Name']])) {
            if (!empty($value)) { // checking if value not empty
                $result[$element['Name']] = ($result[$element['Name']] ?? []);
                // merge it to group wise name result array
                $result[$element['Name']] = array_merge($result[$element['Name']], [$key => $value]);
            }
        }

    }
}

array_merge-合并一个或多个数组
array_key_exists —检查数组中是否存在给定的键或索引

Demo

输出:-

Array
(
    [0] => Array
        (
            [Name] => NAME1
            [Last] => LastValue1
            [Bid] => BidValue1
            [Ask] => AskValue1
        )

    [1] => Array
        (
            [Name] => Name2
            [Last] => LastValue2
            [Bid] => BidValue2
            [Ask] => AskValue2
        )

)

答案 1 :(得分:0)

这是将foreacharray_filter一起使用的最短和简单的解决方案

 foreach($a as &$v){
    $v = array_filter($v);
    isset($r[$v['Name']]) ? ($r[$v['Name']] +=  $v) : ($r[$v['Name']] = $v);
 }

您可以使用array_values重新排列数组的顺序。

工作示例:https://3v4l.org/XeQHa