【问题标题】:Merge two pairs in the same array if the pairs have the same value如果两对具有相同的值,则合并同一数组中的两对
【发布时间】:2015-01-17 02:45:28
【问题描述】:

我有以下对,它们在同一个数组中:

[
 ["ID" => 0, "User" => "Test" , "Type" => 3, "Target" => "Caris"],
 ["ID" => 1, "User" => "Test1", "Type" => 3, "Target" => "Caris"],
 ["ID" => 2, "User" => "Test2", "Type" => 4, "Target" => "Shirone"],
 ["ID" => 3, "User" => "Test3", "Type" => 3, "Target" => "Caris"]
]

我想获取它们的种类,所以我使用以下代码:

$SortList = [];

foreach($Notif as $Key => $Value)
            array_push($SortList, ['Type'   => $Value['Type'], 
                                   'Target' => $Value['Target']]);

然后得到这个:

[
 ["Type" => 3, "Target" => "Caris"], 
 ["Type" => 3, "Target" => "Caris"], 
 ["Type" => 4, "Target" => "Shirone"],
 ["Type" => 3, "Target" => "Caris"]
]

但我真正想要的是这样的:

[
 ["Type" => 3, "Target" => "Caris"], 
 ["Type" => 4, "Target" => "Shirone"]
]

如果它们的值相同,我想合并它们,

(array_merge()好像只能用于非配对)

我怎样才能像上面那样合并它们?

【问题讨论】:

    标签: php arrays sorting keyvaluepair


    【解决方案1】:
    $SortList = [];
    foreach($Notif as $Key => $Value) {
        // Just save only value for the same pair, use them concatenated as the key
        $SortList[$Value['Type']."_".$Value['Target']] =
          array('Type' => $Value['Type'], 'Target' => $Value['Target']);
    }
    // remove extra stuff (the keys) that was added to prevent duplicates
    $SortList = array_values($SortList);
    

    【讨论】:

    • 你或许应该解释一下你在做什么,以及他们在做什么有什么不同。
    • 你只需要$SortList[$Value['Type']]。不要过度复杂化。
    • @AbraCadaver: 同一个类型可能有不同的目标
    • @Jonathan Kuhn:谢谢,添加了内联 cmets。这不是火箭科学,希望现在很清楚。
    • 嗯,用同一个键避免他们重复,天才,我以为有一个函数可以处理这个,没关系,刚刚学会了这个技巧。
    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 2018-05-22
    • 2017-09-28
    • 2021-11-11
    • 2014-03-04
    • 1970-01-01
    • 2018-01-13
    • 2019-03-05
    相关资源
    最近更新 更多