PHP循环MySQL查询结果构建自定义数组仅返回最后一条的解决方法
问题原因
你当前写法的核心问题是PHP不支持在数组字面量定义内部直接用foreach循环批量生成子元素,你写在features数组内的循环逻辑不会自动把每次生成的子项追加到数组中,只会保留最后一次循环的执行结果,因此最终只有1条数据。
修正后的代码
$db->setQuery($query); $item = $db->loadObjectList(); echo $db->getErrorMsg(); //dump($item); // 先初始化固定层级的基础结构 $stores = [ 'type' => 'FeatureCollection', 'features' => [] // 先留空,后续循环追加子项 ]; // 循环查询结果,逐个追加到features数组中 foreach ($item as $i) { $stores['features'][] = [ 'type' => 'Feature', 'geometry' => [ 'type' => 'Point', 'coordinates' => [ $i->lat, $i->lng ] ], 'properties' => [ 'storeImage' => $i->logo, // 你需要自行转换为可访问的实际URL 'storeName' => $i->name, 'phoneFormatted' => $i->phone, // 你需要自行做格式处理 'address' => $i->address, 'city' => $i->city, 'country' => $i->country, 'postalCode' => $i->zip, 'state' => $i->state ] ]; }
内容的提问来源于stack exchange,提问作者Geoff_S
相关产品推荐
相关产品推荐

