【问题标题】:Group arrays if id is the same in angularjs如果 angularjs 中的 id 相同,则对数组进行分组
【发布时间】:2014-10-27 10:33:54
【问题描述】:

我有一个数组,我要输出到一个 json 中,它看起来像这样:

 {
 id: 207
 order_id: 9325
 other_id: 3332
 }
 {
 id: 207
 order_id: 4444
 other_id: 33233
 }
 {
 id: 437
 order_id: 9325
 other_id: 22233
 }

如果 id 相同,我希望它看起来像这样:

 id: 207
     {
       order_id: 9325
       other_id: 3332
     },
     {
       order_id: 4444
       other_id: 33233
     }

等等。

到目前为止,我输出 json 的后端代码如下所示:

    foreach($others as $other)
    {

        if(!empty($other->table_one))
        {
            continue;
        }
        else
        {
            $checks[] = array('id' => $other->id, 'order_id' => $other->order_id, 'other_id' => $other->other_id);
        }
    }

【问题讨论】:

    标签: php json angularjs laravel


    【解决方案1】:

    您的数组中需要另一个级别,因此您可以使用$other->id 作为数组键,并在其下添加包含order_idother_id 的数组。试试这个:

    foreach($others as $other) {
        if(!empty($other->table_one)) {
            continue;
    
        // Create a blank array before trying to use it
        if(!array_key_exists($other->id, $checks))
            $checks[$other->id] = array();
    
        // Add this entry to your array
        $checks[$other->id][] = array(
            'order_id' => $other->order_id,
            'other_id' => $other->other_id
        );
    }
    

    Example(PHP 输出),如果你 json_encode() 它:

    {
        "207": [
            {
                "order_id": 9325,
                "other_id": 3332
            },
            {
                "order_id": 4444,
                "other_id": 33233
            }
        ],
        "437": [
            {
                "order_id": 9325,
                "other_id": 22233
            }
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2018-07-16
      • 2021-11-28
      相关资源
      最近更新 更多