在PHP中从一个文件访问多个json数组


Accessing multiple json arrays from one file in PHP

我在一个PHP文件中存储了多个数组,如下所示:

$animals = array('cat', 'dog', 'bear', 'tiger');
$house = array('couch', 'tv', 'chair', 'table', 'lamp');

我正在从PHP中这样访问:

$animals[0] ---> returns cat
$house[1] ---> returns tv

然而,我需要将所有这些转换为JSON,并将其存储在一个外部文件中。我试过这样做:

{"animals":["cat", "dog", "bear", "tiger"]},
{"house":["couch", "tv", "chair", "table", "lamp"]}

然后我的PHP就像这个

$json = file_get_contents('data/default.json');
$array = json_decode($json, true);

然而,当我试图从这个数组中回显soemething时,它要么会给我一个错误,要么只是一个空白屏幕。

我尝试了多种方法:

$array["animals"][0]
$array[0][0]

我不知道我的问题是json格式还是我访问它的方式,或者我没有将它转换为数组。有人能解释一下应该怎么做吗?

您有以下数组:

$animals = array('cat', 'dog', 'bear', 'tiger');
$house   = array('couch', 'tv', 'chair', 'table', 'lamp');

使用此代码:

$json = json_encode( array( 'animals'=>$animals,'house'=>$house ) );
echo $json;

您将获得此JSON:

{"animals":["cat","dog","bear","tiger"],"house":["couch","tv","chair","table","lamp"]}

使用此代码:

$json = json_encode( array( array('animals'=>$animals),array('house'=>$house) ) );
echo $json;

您将获得此JSON:

[{"animals":["cat","dog","bear","tiger"]},{"house":["couch","tv","chair","table","lamp"]}]

从数组开始时,使用内置函数json_encode获取有效JSON的更好方法。

animals列表..."tiger"]}, <--后面的逗号表示这两个列表是我们在您发布的JSON中没有看到的更大结构的一部分。

尝试将JSON更改为:

{
    "animals": ["cat", "dog", "bear", "tiger"],
    "house": ["couch", "tv", "chair", "table", "lamp"]
}

测试:

$json = '{"animals": ["cat", "dog", "bear", "tiger"],"house": ["couch", "tv", "chair", "table", "lamp"]}';
$array = json_decode($json, true);
echo $array1["animals"][0]."'n";
echo $array1["animals"][1]."'n";
echo $array1["house"][1]."'n";
/* 
Output:
cat
dog
tv
*/

你好,我想你应该试试这种方式

{
    "animals": ["cat", "dog", "bear", "tiger"],
    "house": ["couch", "tv", "chair", "table", "lamp"]
}