猿问

通过 PHP 脚本从 JSON 中提取文本,其中 JSON 输入未知

下面是用户要输入的 JSON,请注意用户可以输入任何 JSON 格式,我只是举个例子。


我需要知道如何通过 PHP 脚本仅从 JSON 中提取文本。请注意 JSON 可以是任何形式或类型,可能不需要如下所示:


{

    "title": "rahul",

    "date": [

        {

            "day": 25,

            "month": "May",

            "year": 2020        }

    ],

    "room": {

        "class": "super",

        "number": 666

    }

}

我需要如下输出:


title rahul

date

day 25

month May

year 2020

room

class super

number 666

我用过json_decode,但它没有正确地给我上面的输出。


凤凰求蛊
浏览 120回答 1
1回答

ibeautiful

json_decode()这将是最好的答案,它将解析任何有效的 JSON 字符串,并返回一个对象或一个数组。鉴于您说过您可以拥有任何 JSON 结构,我创建了一个递归解决方案,它将为您提供所需的输出:<?php$inputJson = <<<JSON{ "title": "rahul", "date": [ { "day": 25, "month": "May", "year": 2020 } ], "room": { "class": "super", "number": 666 } }JSON;if ($decoded = json_decode($inputJson, true)) {&nbsp; &nbsp; outputRecursive($decoded);}function outputRecursive($data) {&nbsp; &nbsp; foreach ($data as $key => $value) {&nbsp; &nbsp; &nbsp; &nbsp; if (is_array($value)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!is_int($key)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $key . PHP_EOL;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outputRecursive($value);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (is_int($key)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $value . PHP_EOL;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo $key . ' ' . $value . PHP_EOL;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}控制台输出:title rahuldateday 25month Mayyear 2020roomclass supernumber 666
随时随地看视频慕课网APP
我要回答