PHP中将数组嵌套存入另一数组(不使用array_push/array_merge)的实现问题
解决PHP数组嵌套提取:保留bus节点数组的独立子数组结构
嘿,作为PHP新手碰到这种嵌套数组处理的问题太正常啦!我帮你一步步搞定这个需求~
首先,你之前的问题核心应该是错误地遍历了每个nodes里的单个元素并推入大数组,导致所有节点被合并成一维。正确的做法是直接把每个bus对应的nodes数组整个作为一个子元素存进结果数组里。
具体实现代码
假设你已经用json_decode($apiJson, true)把接口返回的JSON转成了关联数组,那可以这么写:
// 接口返回的JSON转成PHP数组(你已经完成这一步) $apiData = json_decode($apiResponse, true); // 初始化最终要输出的大数组 $lineCoordinates = []; // 遍历所有sentenceArray项 foreach ($apiData['sentenceArray'] as $item) { // 先做安全校验:确保必要的键存在,避免Undefined index报错 if (isset($item['type'], $item['path']['nodes']) && $item['type'] === 'bus') { // 直接把当前bus的nodes数组作为独立子数组推入大数组 $lineCoordinates[] = $item['path']['nodes']; } } // 转成JSON输出 echo json_encode($lineCoordinates);
举个直观的例子
假设接口返回的原始结构是这样的:
$apiData = [ 'sentenceArray' => [ [ 'type' => 'bus', 'path' => ['nodes' => [['x' => 10, 'y' => 20], ['x' => 30, 'y' => 40]]] ], [ 'type' => 'walk', 'path' => ['nodes' => [['x' => 50, 'y' => 60]]] ], [ 'type' => 'bus', 'path' => ['nodes' => [['x' => 70, 'y' => 80], ['x' => 90, 'y' => 100]]] ] ] ];
运行上面的代码后,$lineCoordinates的结构会是:
[ [['x' => 10, 'y' => 20], ['x' => 30, 'y' => 40]], [['x' => 70, 'y' => 80], ['x' => 90, 'y' => 100]] ]
转成JSON后就是你想要的lineCoordinates目标结构啦~
额外提示
加isset()判断是为了防止接口返回的数据结构异常时(比如某个bus项没有path或nodes键),代码直接报错。作为新手,养成校验数组键存在的习惯能减少很多调试麻烦哦!
内容的提问来源于stack exchange,提问作者gimmeonereason
相关产品推荐
相关产品推荐

