如何在PHP中将对象转换为特定格式的数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在PHP中将对象转换为特定格式的数组相关的知识,希望对你有一定的参考价值。
我有一个像JSON这样的对象
[{"schedule_time_id":1},{"schedule_time_id":2}]
我想将此JSON对象转换为以下格式
[1,2]
我已经使用(array) $object
来转换它,但没有得到目标格式。
答案
你有一个json字符串。您可以使用json_decode
将其转换为关联数组
喜欢:
$str = '[{"schedule_time_id":1},{"schedule_time_id":2}]';
$arr = json_decode( $str, true );
echo "<pre>";
print_r( $arr );
echo "</pre>";
这看起来像:
Array
(
[0] => Array
(
[schedule_time_id] => 1
)
[1] => Array
(
[schedule_time_id] => 2
)
)
如果要将其转换为简单数组(非关联数组),可以使用array_column
$newArr = array_column( $arr, 'schedule_time_id' );
echo "<pre>";
print_r( $newArr );
echo "</pre>";
这将导致:
Array
(
[0] => 1
[1] => 2
)
为了缩短它,您可以:
$str = '[{"schedule_time_id":1},{"schedule_time_id":2}]';
$newArr = array_column( json_decode( $str, true ) , 'schedule_time_id' );
另一答案
有很多可能性来实现这一目标。其中之一是在解码的json上使用数组映射。
$result = array_map(function ($item) {
return $item->schedule_time_id;
}, json_decode($json));
以上是关于如何在PHP中将对象转换为特定格式的数组的主要内容,如果未能解决你的问题,请参考以下文章