使用PHP在JSON数组内部检索更多数据

时间:2018-01-27 15:41:31

标签: php arrays json

我有一个JSON文件,我想填写一个表格,但是不能完全弄清楚如何检索内部数据并通过数组循环以获取我制作的表格。

这是我的JSON文件:test.JSON:

    ionic cordova run browser -- --port=8100

然后使用PHP我使用了:test.PHP:

{
"data":{
 "Chair":{
    "id":24,"key":"Chair","name":"Chair","title":"oak home made"
 },
 "Table":{
    "id":37,"key":"Table","name":"Table","title":"round white table"
 },
 "Closet":{
    "id":18,"key":"Closet","name":"Closet","title":"big and red"
 },
 "Sofa":{
    "id":110,"key":"Sofa","name":"Sofa","title":"room for five persons"
 }
},
"type":"furniture","version":"1.1.0"
}

这就是我得到的:

$url = 'test.json';
$result=file_get_contents($url);
$decoded=json_decode($result, true);
var_dump($decoded);

然后我试图检索"主席","表","壁橱"和"沙发",但我不知道该怎么做。当我尝试这个时:

array(3) { ["data"]=> array(4) 
 { 
 ["Chair"]=> array(4) 
   { ["id"]=> int(24) ["key"]=> string(5) "Chair" ["name"]=> string(5) "Chair" ["title"]=> string(13) "oak home made" } 
 ["Table"]=> array(4) 
   { ["id"]=> int(37) ["key"]=> string(5) "Table" ["name"]=> string(5) "Table" ["title"]=> string(17) "round white table" } 
 ["Closet"]=> array(4) 
   { ["id"]=> int(18) ["key"]=> string(6) "Closet" ["name"]=> string(6) "Closet" ["title"]=> string(11) "big and red" } 
 ["Sofa"]=> array(4) 
   { ["id"]=> int(110) ["key"]=> string(4) "Sofa" ["name"]=> string(4) "Sofa" ["title"]=> string(21) "room for five persons" } 
 } 
 ["type"]=> string(9) "furniture" ["version"]=> string(5) "1.1.0" 
} 

我得到: 关键:数据

value:Array

有人可以帮助我获得"主席","表"," Closet"和#34;沙发",包括每一个" id,key,name和title?

我收到了导游,但他们不会帮助我,因为我觉得这种类型的"阵列"与我收到的指南的链接不同。

谢谢!

2 个答案:

答案 0 :(得分:2)

您正在循环浏览最高级别的array,而您想要的级别低于能够遍历elements data foreach ($summonerDecoded2['data'] as $key => $value) { echo "key: ".$key."</br>"; echo "value id: ".$value['id']."</br>"; echo "value key: ".$value['key']."</br>"; echo "value name: ".$value['name']."</br>"; echo "value title: ".$value['title']."</br>"; } 的所有级别,例如这样:

$url = 'test.json';
$result=file_get_contents($url);
$decoded = json_decode($result, true);

foreach ( $decoded["data"] as $key => $value) {
    echo $value[ "key" ];
    echo "<br />";

   //You can access data by:
   /*
    echo $value[ "id" ];
    echo $value[ "key" ];
    echo $value[ "name" ];
    echo $value[ "title" ];
   */
}

答案 1 :(得分:1)

你可以这样做:

Chair
Table
Closet
Sofa

这将导致:

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({name: 'ObjKeys'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    return Object.keys(value);
  }
}