如果在angularjs中id相同,则组数组

时间:2014-09-03 03:05:54

标签: php json angularjs laravel

我有一个阵列,我正在吐出一个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);
        }
    }

1 个答案:

答案 0 :(得分:0)

您需要在数组中使用其他级别,以便可以使用$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
        }
    ]
}