简体   繁体   English

PHP数组和Json解码错误

[英]PHP array and Json decode errors

Please help as I have spent two days on this... 请帮忙,因为我已经花了两天时间...

I have a JSON object. 我有一个JSON对象。 as shown below. 如下所示。

[{"attr":{"id":"node_8","rel":"folder"},"data":"_demo","state":"closed"},{"attr":        {"id":"node_13","rel":"folder"},"data":"demo3","state":""}][{"attr":{"id":"node_8","rel":"folder"},"data":"_demo","state":"closed"},{"attr":{"id":"node_13","rel":"folder"},"data":"demo3","state":""}]string(140) "[{"attr":{"id":"node_8","rel":"folder"},"data":"_demo","state":"closed"},{"attr":{"id":"node_13","rel":"folder"},"data":"demo3","state":""}]" 

Using Json decode I get the following output.. 使用Json解码,我得到以下输出。

Array ( [0] => Array ( [attr] => Array ( [id] => node_8 [rel] => folder ) [data] => _demo [state] => closed ) [1] => Array ( [attr] => Array ( [id] => node_13 [rel] => folder ) [data] => demo3 [state] => ) ) aArray

How can I iterate through and access each value as a list so I can add div classes, and id's. 我该如何遍历并以列表的形式访问每个值,以便添加div类和id。 For instance [id] => node_8. 例如[id] => node_8。 How can I access that value and convert it to div id = "node_8", or [rel] => folder, and convert to div class = "folder". 我如何访问该值并将其转换为div id =“ node_8”或[rel] =>文件夹,然后转换为div class =“ folder”。 For example I hope that makes sense 例如,我希望这是有道理的
for example 例如

 foreach ($data as $key => $value){
    if(is_array($value)) {
    {

     echo $value . "<br />";
     }
    }
  } 

which produces id = node_8 rel = folder data = _demo state = closed id = node_13 rel = folder data = demo3 state = 产生id = node_8 rel =文件夹数据= _demo状态=已关闭id = node_13 rel =文件夹数据= demo3状态=

I have added the answer below if anyone has problems with multi dimension arrays, and decoding from JSON, adding divs etc to the array. 如果有人在多维数组,从JSON解码,将div等添加到数组方面遇到问题,我已经在下面添加了答案。 Kindly provided by Shayan Husaini. 由Shayan Husaini提供。 Where $string is equal to array. 其中$ string等于array。

$json_a=json_decode($string,true);
foreach ($json_a as $value) {

echo ' 回声
'; '; echo 'id: '.$value['attr']['id']; echo'id:'。$ value ['attr'] ['id']; echo ' 回声
'; '; echo 'rel: '.$value['attr']['rel']; echo'rel:'。$ value ['attr'] ['rel']; echo ' 回声
'; '; echo 'name: '.$value['data']; echo'name:'。$ value ['data']; echo ' 回声
'; '; echo '' .$value['state']; echo''。$ value ['state']; echo ''; 回声'';

Your array is multidimensional array so you need to define the keys as well for child arrays to get the values. 您的数组是多维数组,因此您还需要定义键,以使子数组获取值。 I hope this would help you: 我希望这对您有帮助:

foreach ($data as $value){
       echo 'id: '.$value['attr']['id'];
       echo 'rel: '.$value['attr']['rel'];
       echo 'demo: '.$value['demo'];
       echo 'state: '.$value['state'];
  } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM