doucheng1063 2011-09-04 22:40 采纳率: 100%
浏览 56
已采纳

PHP从多维数组中查找值,然后将它们放在数组中

I have an array which contains a set of information from a database, but some of it is a duplicate with just 1 value in the deepest part of the array changed. For example:

[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => "stuff1" )
[2] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => "stuff2" )
[3] => Array( ['id'] => 3 , ['name'] => "Third Array" , ['more'] => "stuff3" )
[4] => Array( ['id'] => 3 , ['name'] => "Third Array" , ['more'] => "stuff4" )

What I'm trying to do is get any arrays with the same ['id'] field into an array with an array instead of ['more']. For example:

[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => Array( [0] => "stuff1" , [1] => "stuff2" ) )
[2] => Array( ['id'] => 2 , ['name'] => "Third Array" , ['more'] => Array( [0] => "stuff3" , [1] => "stuff4" ) )

I have tried to do this a few ways, but the closest I can get is a function which will put all the ['more'] values into 1 array like this:

[0] => Array( ['id'] => 1 , ['name'] => "First Array" , ['more'] => "stuff" )
[1] => Array( ['id'] => 2 , ['name'] => "Second Array" , ['more'] => Array( [0] => "stuff1" , [1] => "stuff2" , [2] => "stuff3" , [3] => "stuff4" ) )

And that is from this function:

<?php
private function compress_duplicates( $a = array() ) {
    $diff_key = array_diff_key( $a , array_unique( $a ) );
    $first_key = array_shift(array_keys($diffkey));
    $array["id"] = $diff_key[$first_key]["id"];
    $array["name"] = $diff_key[$first_key]["name"];
    foreach($diff_key as $term) {
        $array["more"][] = $term["more"];
    }
    return $array;
}
?>

Basically what I'm asking: How can I find duplicates in a multidimensional array and then place each of those duplicates into their own array?

  • 写回答

1条回答 默认 最新

  • douwen4125 2011-09-04 22:50
    关注
    $result = array();
    foreach ($array as $elem) {
        if (isset($result[$elem['id']])) {
            $result[$elem['id']]['more'] = array_merge((array)$result[$elem['id']]['more'],
                                                       array($elem['more']));
        } else {
            $result[$elem['id']] = $elem;
        }
    }
    

    Optionally followed by a $result = array_values($result) if you want to reset the keys of the $result array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度