PHP:如何将多维数组转回含stdClass Object的数组?
问题:将多维数组转回外层为数组、元素为stdClass Object的结构
场景还原
初始结构:包含stdClass Object的数组
Array ( [0] => stdClass Object ( [ID] => 5384 [post_title] => Accordeon me con jQuery [post_name] => accordeon-con-jquery [readings] => 55140 [post_date] => 01-12-2012 [media] => 59.546436285097 [dias] => 926 ) [1] => stdClass Object ( [ID] => 2509 [post_title] => Popup me con jQuery [post_name] => popup-me-con-jquery [readings] => 26261 [post_date] => 13-04-2012 [media] => 22.677892918826 [dias] => 1158 ) ...
将其转为多维数组的代码:
$visits = json_decode(json_encode($visits), true);
转换后得到符合预期的多维数组:
Array ( [0] => Array ( [ID] => 5384 [post_title] => Accordeon me con jQuery [post_name] => accordeon-con-jquery [readings] => 55140 [post_date] => 01-12-2012 [media] => 59.546436285097 [dias] => 926 ) [1] => Array ( [ID] => 2509 [post_title] => Popup me con jQuery [post_name] => popup-me-con-jquery [readings] => 26261 [post_date] => 13-04-2012 [media] => 22.677892918826 [dias] => 1158 ) ...
尝试转回时使用以下代码,得到意外结果(外层为stdClass Object):
$visits = json_decode(json_encode($visits));
意外结果:
stdClass Object ( [0] => stdClass Object ( [ID] => 5384 [post_title] => Accordeon me con jQuery [post_name] => accordeon-con-jquery [readings] => 55140 [post_date] => 01-12-2012 [media] => 59.546436285097 [dias] => 926 ) [1] => stdClass Object ( [ID] => 2509 [post_title] => Popup me con jQuery [post_name] => popup-me-con-jquery [readings] => 26261 [post_date] => 13-04-2012 [media] => 22.677892918826 [dias] => 1158 ) ...
解决方案
方法1:使用array_map遍历转换
通过array_map将数组中的每个子数组转为stdClass对象,外层保持数组结构:
$visits = array_map(function($item) { return (object)$item; }, $visits);
方法2:重置数组索引后再用JSON转换
如果原多维数组的索引不连续(存在间隙或非数字键),json_encode会将其转为JSON对象,导致json_decode返回外层为stdClass。此时可先用array_values重置索引为连续数字,再进行转换:
$visits = json_decode(json_encode(array_values($visits)));
方法3:手动foreach遍历转换
手动遍历数组,将每个子数组转为stdClass并添加到新数组中:
$newVisits = []; foreach ($visits as $item) { $newVisits[] = (object)$item; } $visits = $newVisits;
内容的提问来源于stack exchange,提问作者plasticheart
相关产品推荐
相关产品推荐

