You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:39:58