dongyan2445 2014-05-22 11:29
浏览 57
已采纳

如何解码json并将json中的值设置为php可用?

i have json $json like this

{"name":"peter","availability":"available"}

i want to decode and set value to php available and echo but not any show ?, i use this code

<?PHP
                 $decode = json_decode($json, true);
                 $availability = $decode[availability];
                 echo $availability;  
?>

where is wrong ?

  • 写回答

3条回答 默认 最新

  • douyan1321 2014-05-22 11:31
    关注

    Use as

    $availability = $decode["availability"];
    

    If you use

    $availability = $decode[availability];
    

    It will raise a notice as

    Notice: Use of undefined constant availability - assumed 'availability'
    

    However your code is correct is should display the value with the above notice unless the $json string is not the one you have added.

    Your code

    <?php 
    $arr = array('name' => peter, 'availability' => available); 
    $json = json_encode($arr); 
    $decode = json_decode($json, true); 
    $availability = $json_decode[availability]; 
    print_r($json); 
    echo $availability; 
    ?>
    

    Now this is what you are doing

    $decode = json_decode($json, true); 
    $availability = $json_decode[availability]; 
    

    You are using a different array name $json_decode instead of $decode

    So the correct way is

    $arr = array('name' => 'peter', 'availability' => 'available'); 
    $json = json_encode($arr); 
    $decode = json_decode($json, true); 
    $availability = $decode['availability']; //print_r($json); 
    echo $availability;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改