如何合并数组并使其成为关联数组

时间:2017-10-17 07:11:13

标签: php laravel-5

*您好!我正在处理我的任务,在查询我的表之后。它给了我这个结果*

Collection {#499
  #items: array:3 [
    0 => {#497
      +"id": 1
      +"text": "Category 1"
      +"sub": "sub-cat 1"
      +"question": "first question"
      +"description": "category first description"
    }
    1 => {#501
      +"id": 2
      +"text": "Category 1"
      +"sub": "sub-cat 2"
      +"question": "second question"
      +"description": "category second description"
    }
    2 => {#502
      +"id": 3
      +"text": "Category 2"
      +"sub": "another sub-cat"
      +"question": "third question"
      +"description": "category third description"
    }
  ]
}

我需要将其转换为此

Collection {#499
      #items: array:3 [
        0 => {#497
          +"id": 1
          +"text": "Category 1"
          +"sub": "sub-cat 1"
                [{
                  +"question": "first question"
                  +"description": "category first description"
                }]

         +"sub": "sub-cat 2"
                [{
                 +"question": "second question"
                 +"description": "category second description"
                }]
        }

        1 => {#502
          +"id": 3
          +"text": "Category 2"
          +"sub": "another sub-cat"
          +"question": "third question"
          +"description": "category third description"
        }
      ]
    }

我需要将一个数组与相同的键合并,并将其作为关联数组 提前致谢

1 个答案:

答案 0 :(得分:0)

这样的东西?

$results = [];
foreach ($mycollection as $v) {
    if (!isset($results[$v->text])) {
        $results[$v->text] = [
            'id' => $v->id,
            'text' => $v->text,
            'sub' => []
        ];
    }

    $results[$v->text]['sub'][$v->sub] = [
        'question' => $v->question,
        'description' => $v->description
    ];
}

// If you want a numeric index for your array :
// $results = array_values($results);
相关问题