gpt4 book ai didi

php - 对 stdClass 对象使用 array_walk_recursive()

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:34:34 26 4
gpt4 key购买 nike

我已经查看了这里的一些答案,但似乎没有使用这种方法?

我有一个项目数组,项目是对象。该对象可以有一个键,它是“children”,“children”是一个对象数组等。

有什么办法可以实现吗?

示例:

    Array
(
[1] => stdClass Object
(
[id] => 1
[name] => Steve King
[image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg
[parent] => 0
[children] => Array
(
)

)

[2] => stdClass Object
(
[id] => 2
[name] => Eden Hall
[image] => upload/shop/064f60a98deba612e437ac549f1dc05d.jpg
[parent] => 0
[children] =>Array
(
[1] => stdClass Object
(
[id] => 1
[name] => Steve King
[image] => upload/shop/fe7a66254e4249af2b0093efca75a914.jpg
[parent] => 0
[children] => Array
(
)

)
)
[3] => stdClass Object
(
[id] => 3
[name] => Paula Johnson
[image] => upload/shop/1492a323090afbad07c35cf93fe6bdda.jpg
[parent] => 0
[children] => Array
(
)

)

[4] => stdClass Object
(
[id] => 4
[name] => Ethan Watson
[image] => upload/shop/677c720333af33bc58d0684d79918e03.jpg
[parent] => 0
[children] => Array
(
)

)

[5] => stdClass Object
(
[id] => 5
[name] => Abigail Adams
[image] => upload/shop/da1734277322fc3b2e84a9ddbcc2e2f1.jpg
[parent] => 0
[children] => Array
(
)

)

最佳答案

$array 下分配一个对象数组。

解决方案一: json_encode 一个对象数组使其成为一个json,然后将一个json转换成关联数组

$result=json_decode(json_encode($array),true);
array_walk_recursive($result, function($value,$key){
print_r($value);
print_r($key);
});

解决方案 2:遍历数组并将每个 object 类型转换为 array

array_walk($array,function(&$value,$key){
$value=(array) $value;
});
array_walk_recursive($array, function($value,$key){
print_r($value);
print_r($key);
});

关于php - 对 stdClass 对象使用 array_walk_recursive(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com