簡體   English   中英

如何在數組中綁定相同的鍵值?

[英]How to bind the same key value in 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;
}

使用此代碼我沒有得到我想要的輸出。

我錯過了什么?

作為它的對象,你可以這樣做,

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

這是我在普通數組中所做的:

$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'] ]之后添加 [ [ $person['category'] ]

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

您可以使用 Laravel 集合:

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

Persons::all()已經返回了一個充滿Person模型實例的集合,所以你可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM