douhuang1973 2014-01-09 12:25
浏览 72
已采纳

json_encode数组的特定部分

$array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
$json=json_encode($array);
echo $json

By this way I am reading all the data, but how can I read the data of only Real or Inter?

For example, if it is json_decoded I can do so:

  1. For Inter:

    echo $array['Inter'];
    
  2. For Real:

    foreach($array["Real"] as $real){ 
        echo $real."<br>";
    }
    

How can I do the same with json_encode()?

  • 写回答

2条回答 默认 最新

  • douyouqian8550 2014-01-09 12:34
    关注

    As I understand your question you need to output the json`d object.

    Input

    $input = '{"Real":["Alonso","Zidan"],"Inter":"Zanetti","Roma":"Toti"}';
    

    In php:

    // Second true is for array return, not object)
    $string = json_decode($input, true) 
    echo $string['Inter'];
    

    In Javascript (jQuery):

    var obj = jQuery.parseJSON(input);
    if (obj != undefined) {
        echo obj['Inter'];
    }
    

    UPD:

    If you need to get an json in all arrays you need to make follow:

    $array = array("Real" => array("Alonso","Zidan"),"Inter" => "Zanetti", "Roma" => "Toti");
    foreach($array as $key => $value) {
        $array[$key] = json_encode($value);
    }
    

    After this code all variables in array will be json`ed and you can echo them in any time

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM