如何动态地从JSON文件中获取数组

时间:2017-04-08 17:10:28

标签: php json

我有Json文件,其中包含很多数组。如何通过名称(例如get参数)为每个人动态获取数组。

JSON

Unit

PHP

[{
    "Name": "Somename",
    "Lastname": "somelastname",
     "Address": "someaddress",
},
{
    "Name": "Somename1",
    "Lastname": "somelastname1",
      "Address": "someaddress1",
},
{
    "Name": "Somename2",
    "Lastname": "somelastname2",
     "Address": "someaddress2",
}}

HTML

<?php

error_reporting(0);

$json_file = file_get_contents('jsonfile.json');

$someArray = json_decode($json_file, true); 

?> 

1 个答案:

答案 0 :(得分:0)

我不知道你究竟需要做什么(只找到一个匹配,或者全部取得),但这适用于:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$array = array(
1 => array( "Name" => "Somename1", "Lastname" => "somelastname1", "Address" => "someaddress1"),
2 => array( "Name" => "Somename2", "Lastname" => "somelastname2", "Address" => "someaddress2"),
3 => array( "Name" => "Somename3", "Lastname" => "somelastname3", "Address" => "someaddress3"),
4 => array( "Name" => "Somename4", "Lastname" => "somelastname4", "Address" => "someaddress4")
);

$data1 = json_encode($array);
//var_dump($data1);

$data = json_decode($data1, true);
//var_dump(json_decode($data1));

$myname = "Somename3";

/* one liner to get one result */

if( array_search("$myname", array_column($data, 'Name')) == true ){ echo"[ $myname found ! ]"; } else { echo"[ no data match ! ]"; }

/* loop to get all results */

foreach($data as $user){
echo $user['Name'].' '.$user['Lastname'].' '.$user['Address'].'<br/>'; 
}

?>