如何获取多个数组JSON数据

时间:2018-04-10 10:10:01

标签: php json

我有多个数组的Json Data,我尝试将数据放在effect_property中,但它不会返回任何内容。

这是我的代码

$json = file_get_contents('data.json');
$json_data = json_decode($json,true);

for($i = 0; $i < $count_data_action; $i++){
    $path_data_action =  $json_data[t03_action][data][$i][effect_property];
}

当我打印$ path_data_action时,它会显示如下内容:

{"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}

我如何获得source_path?

3 个答案:

答案 0 :(得分:1)

您正在解码的JSON可能是:

$json_data = json_decode($json,true);

effect_property 键处包含另一个JSON字符串。您可以将其更改为JSON对象,它应该可以正常工作。
否则,您可以再次使用 json_decode ,例如:

for($i = 0; $i < $count_data_action; $i++){
     $path_data_action =  $json_data[t03_action][data][$i]effect_property];
     $pathDataActionArr = json_decode($path_data_action , true);
     $sourcePath = $pathDataActionArr['propTo']['sourcePath'];
}

此外,通过JSON编码/解码来了解最后发生的错误 json_last_error — Returns the last error occurred

更新:我尝试使用代码解码您发布的JSON:

$fileContent = file_get_contents("/home/tarun/Desktop/test/abcd");
$jsonArray = json_decode($fileContent,true);
var_dump($jsonArray['t03_action']['data'][9]['effect_property']);
$effectPropertyArr = json_decode($jsonArray['t03_action']['data'][9]['effect_property'],true);

if(isset($effectPropertyArr['propTo']['source_path'])) {
    var_dump($effectPropertyArr['propTo']['source_path']);  
} else {
    var_dump("No such key!");
}

此处,并非键 effect_property 中数组的所有元素都包含 source_path 。这就是原因:

if(isset($effectPropertyArr['propTo']['source_path'])) {

以上工作正常,输出:

  

/home/tarun/Desktop/test/temp.php:6:   string(205)“{”duration“:1,”delay“:0,”propTo“:{”source“:”image“,”source_path“:”../ uploads / 18032022375907620062 /“,”source_file“:” 1804100413270066.jpg “ ”SOURCE_NAME“: ”Penguins.jpg“}, ”beforeAction“: ”0“, ”action_order“: ”1“}”   /home/tarun/Desktop/test/temp.php:10:   string(32)“../ uploads / 18032022375907620062 /”

答案 1 :(得分:0)

// decoded array passed key of that array
$json_data['propTo']['source_path'];

答案 2 :(得分:0)

try this ,Its working for me.

  var data =  {"duration":1,"delay":0,"propTo":{"source":"image","source_path":"../uploads/17041409353289557288/","source_file":"1704141604180616.jpg","source_name":"image1.jpg"},"beforeAction":"0","action_order":"1"}
            alert(data.duration);
            var Prop = data.propTo;
            alert(Prop.source_path);`enter code here`