php - 将对象的对象转换为对象数组(PHP、Laravel)

标签 php arrays laravel object type-conversion

我正在使用 Eloquent 从数据库返回一些数据并放入数组对象中。我对浏览器的响应对象以这种格式显示:

// response()->json($response, 200);


[{
"id": 1,
"name": "car",
"make": ["bmw", "ford"]
"order": 1
},
{
"id": 2,
"name": "bike",
"make": ["aprilia"]
"order": 2
},
{
"id": 3,
"name": "boat",
"make": []
"order": 3
 },
(...)
]

不过,在返回之前,我想在服务器端对其进行过滤。所以我只返回在 "make" 数组中保存值的对象。

所以我正在运行这个循环:

        foreach ($response as $key => $transport) {

            if (count($response[$key]['make']) == 0) {
                unset($response[$key]);
            };

        }

php 所做的是将数组转换为对象,并向每个内部对象添加键。所以现在我的 $response 看起来像:


// response()->json($response, 200);


{ // notice here it has changed from array to object
  "0": { // notice here it has added key "0"
    "id": 1,
    "name": "car",
    "make": ["bmw", "ford"]
    "order": 1
  },
    "1" : { // notice here it has added key "1"
    "id": 2,
    "name": "bike",
    "make": ["aprilia"]
    "order": 2
  },
 (...)
}

首先 - 为什么? 第二个问题 - 如何防止/返回对象数组响应?

最佳答案

当您从 PHP 中的索引数组中取消设置值时,现有索引将保留。使用一个包含小范围整数的简单示例来说明,以下代码取消设置数组中的所有奇数整数:

$numbers = range(1, 5); // [1, 2, 3, 4, 5];

foreach ($numbers as $index => $number) {
    if ($number % 2 !== 0) {
        unset($numbers[$index]);
    }
}

print_r($numbers);

产生:

Array
(
    [1] => 2
    [3] => 4
)

请注意,奇数元素被移除,但现有元素的索引被保留。由于存在这些间隙,此时数组未按顺序编制索引。

这样做的结果是,当您json_encode() 这个数组时,它假定要保留这些非顺序索引(此时我们称它们为键),因此它创建一个带有键的对象文字。这些键是恰好是整数的字符串:

echo json_encode($numbers); // {"1":2,"3":4} 

使用 array_values($numbers) 将重置数组的索引:

$reindexed = array_values($numbers);
echo json_encode($reindexed); // [2, 4]

注意:我在评论中提到您可以使用 (array) 转换为数组——这实际上是不正确的,因为它将保留非顺序索引。

希望这对您有所帮助!

关于php - 将对象的对象转换为对象数组(PHP、Laravel),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55905011/

相关文章:

php - 从 While 循环填充 PHP 数组

php - Laravel - 将资源路由覆盖到不同的路由过滤器组

javascript - meteor js |通过助手在 View 中显示 Json

mysql - 按相关表列排序表的最快方法

php - Laravel Doctrine 仅从 findAll() 查询返回单个属性

php - 下面的 driver_options 参数是什么意思?

php - 如何将 Python 加密转换为 PHP?

php - SQL 查询在 CodeIgniter 中不起作用?

php - MySQL:如果此 ip 没有任何记录,则插入

php - 从特定键的嵌套数组行收集所有值