Laravel 集合 where 返回的資料格式問題

haibin_hu發表於2018-07-29

where以一對指定的「鍵/數值」篩選集合:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Bookcase', 'price' => 150],
    ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);

$filtered->all();

/*
[
    ['product' => 'Chair', 'price' => 100],
    ['product' => 'Door', 'price' => 100],
]
*/

實際執行結果是:

$collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);
return response()->json($filtered->all());
/*
// json結果裡把索引當做了key
{
    "1": {
        "product": "Chair",
        "price": 100
    },
    "3": {
        "product": "Door",
        "price": 100
    }
}

// dd後的結果,key不連續了
array:2 [
  1 => array:2 [
    "product" => "Chair"
    "price" => 100
  ]
  3 => array:2 [
    "product" => "Door"
    "price" => 100
  ]
]
*/

使用array_values後的結果:

$collection = collect([
        ['product' => 'Desk', 'price' => 200],
        ['product' => 'Chair', 'price' => 100],
        ['product' => 'Bookcase', 'price' => 150],
        ['product' => 'Door', 'price' => 100],
]);

$filtered = $collection->where('price', 100);
$filteredAll = array_values($filtered->all());
dd($filteredAll);
return response()->json($filteredAll);

/*
[
    {
        "product": "Chair",
        "price": 100
    },
    {
        "product": "Door",
        "price": 100
    }
]

array:2 [
  0 => array:2 [
    "product" => "Chair"
    "price" => 100
  ]
  1 => array:2 [
    "product" => "Door"
    "price" => 100
  ]
]
*/

應該和json_encode有關,連續索引0、1、2這樣的轉換後不轉換索引為key,不連續的就會把索引轉換為key
所以where查詢後需要將陣列索引重置
這裡使用array_values,也可以使用

$filteredAll = array_merge($filtered, []);

$filteredAll = $filtered->all();
sort($filteredAll);

查詢後得到結果:
jsonencode()只將索引陣列(indexed array)轉為陣列格式,而將關聯陣列(associative array)轉為物件格式
比如,現在有一個索引陣列

  $arr = Array('one', 'two', 'three');   
  echo json_encode($arr);  

結果為:

  ["one","two","three"]  

如果將它改為關聯陣列:

  $arr = Array('1'=>'one', '2'=>'two', '3'=>'three');   
  echo json_encode($arr);  

結果就變了:

  {"1":"one","2":"two","3":"three"}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章