如何在Laravel(PHP)中访问JSON文件的所有name属性?
在Laravel中提取动态键JSON里的所有"name"属性
嘿,我来帮你搞定这个问题!你的JSON结构确实有点嵌套,外层是二维数组包裹着带动态键的对象,不过用Laravel的集合和数组工具类就能轻松提取所有的name属性,不管键名是动态的还是固定的。
步骤1:解析JSON字符串
首先,你需要把JSON字符串转换成PHP数组。如果你的JSON是存储在文件里的,可以用Laravel的Storage门面读取;如果是接口返回的直接用字符串处理就行:
// 假设你的JSON字符串存在$jsonString变量中 // 如果是从文件读取:$jsonString = Storage::get('path/to/your/hospitals.json'); $array = json_decode($jsonString, true); // 可选:验证JSON解析是否成功 if (json_last_error() !== JSON_ERROR_NONE) { throw new \RuntimeException('Invalid JSON format'); }
步骤2:提取核心数据结构
你的JSON外层是[[{...}]]这种二维数组,所以我们需要先拿到最内层的那个带动态键的对象:
use Illuminate\Support\Arr; // 取出最内层的医院对象集合 $hospitalObjects = Arr::first(Arr::first($array)); // 验证结构是否符合预期 if (!is_array($hospitalObjects)) { throw new \RuntimeException('Unexpected data structure in JSON'); }
步骤3:收集所有"name"属性
接下来我们用Laravel的集合来高效收集所有name,包括医院名称和专科名称:
方式1:简洁的链式操作(推荐)
use Illuminate\Support\Collection; $allNames = collect($hospitalObjects) ->flatMap(function ($hospital) { // 先收集医院名称 $names = [$hospital['name']]; // 如果有专科列表,收集里面的名称 if (isset($hospital['specializations']) && is_array($hospital['specializations'])) { $names = array_merge($names, collect($hospital['specializations'])->pluck('name')->toArray()); } return $names; }); // 转成普通数组(可选) $allNamesArray = $allNames->toArray();
方式2:传统循环(适合新手理解)
$allNames = []; foreach ($hospitalObjects as $hospital) { // 添加医院名称 $allNames[] = $hospital['name']; // 遍历专科列表添加名称 if (isset($hospital['specializations']) && is_array($hospital['specializations'])) { foreach ($hospital['specializations'] as $specialization) { $allNames[] = $specialization['name']; } } }
最终结果示例
运行上面的代码后,$allNames(或$allNamesArray)会包含所有的name值:
[ "Asiri Medical Hospital - Kirula Road - Colombo 05", "Endocrinologist", "Diabetologist", "Asiri Central Hospital - Norris Canal Road-Colombo ..." ]
内容的提问来源于stack exchange,提问作者Pasan Kavinga
相关产品推荐
相关产品推荐

