如何在数组中绑定相同的键值?

时间:2019-04-11 07:19:57

标签: php arrays laravel multidimensional-array

当前在阵列中遇到问题。我无法获得想要的输出。

这是我的数组。

[
 {
  "id": 1,
  "name": "Antonio Trillanes",
  "category": "libel" 
 },
 {
  "id": 2,
  "name": "Liela De Lima",
  "category": "libel" 
 },
 {
  "id": 3,
  "name": "Gloria Macapagal Arroyo",
  "category": "plunder" 
 },
]

这是我想要的输出。

我想要这种方式。

[
 libel: [
          {
           "id": 1,
           "name": "Antonio Trillanes",
           "category": "libel" 
          },
          {
           "id": 2,
           "name": "Liela De Lima",
           "category": "libel" 
          }
        ],
 plunder: [
           {
            "id": 3,
            "name": "Gloria Macapagal Arroyo",
            "category": "plunder" 
           },
          ]
]

这是我的代码。

$convicted_persons = [];
$persons = Persons::all();
foreach($persons as $person) {
     $convicted_persons [ $person['category'] ] = $person;
}

我无法使用此代码获得所需的输出。

我错过了什么?

4 个答案:

答案 0 :(得分:2)

您可以通过这种方式将其作为对象

$temp = [];
foreach ($arr as $key => $value) {
    $temp[$value->category][] = $value; // if not object $temp[$value['category']][] = $value;
}
print_r($temp);die;

答案 1 :(得分:2)

只需更改select f1, CASE WHEN PROD_CD = 'ESALE' THEN SUM (prod_count) WHEN PROD_CD = 'RSALE' THEN (SUM (prod_count) * -1) ELSE 0 END AS SALEQTY, ,如下所示:-

foreach()

答案 2 :(得分:2)

这是我在普通数组中所做的:

$array = array(
        array(
            "id" => 1,
            "name" => "Antonio Trillanes",
            "category" => "libel"
        ),
        array(
            "id" => 2,
            "name" => "Liela De Lima",
            "category" => "libel"
        ),
        array(
            "id" => 3,
            "name" => "Gloria Macapagal Arroyo",
            "category" => "plunder"
    ));
    $new_array = array();
    foreach ($array as $value){
        $new_array[$value['category']][] = $value;
    }

只需按以下方式更新您的行,只需在[ $person['category'] ]之后添加[]:

$convicted_persons [ $person['category'] ] = $person;
$convicted_persons [ $person['category'] ][] = $person;

答案 3 :(得分:1)

您可以使用Laravel集合:

https://laravel.com/docs/5.8/collections#method-groupby

Persons::all()已经返回了一个填充有Person模型实例的集合,因此您可以执行以下操作:

$persons = Persons::all();
$convicted_persons = $persons->groupBy('category');