【问题标题】:How to parse array JSON to PHP Object?如何将数组 JSON 解析为 PHP 对象?
【发布时间】:2019-02-12 09:19:27
【问题描述】:

当我想使用循环 foreach 将我的 json 数组解析为 php 对象时出现错误。

这是我的错误:

警告:为 foreach() 提供的参数无效 C:\xampp\htdocs\testJSON\crul_json.php 第 49 行

然后这是我的代码

<?php

function http_request($url){
    // persiapkan curl
    $ch = curl_init(); 

    // set url 
    curl_setopt($ch, CURLOPT_URL, $url);

    // set user agent    
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');

    // return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    // $output contains the output string 
    $output = curl_exec($ch); 

    // tutup curl 
    curl_close($ch);      

    // mengembalikan hasil curl
    return $output;
}

$profile = http_request("http://localhost/testWebService/");

//json_output(400, $profile);

$json_format = json_encode($profile);
//echo $json_format;

// ubah string JSON menjadi array
$hasil = json_decode($json_format, TRUE);
$hdcode = var_dump($hasil);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Curl Data JSON</title>
</head>

<body>

<br>
<p> 
    <?php
    foreach ($hasil  as $i):   
    ?>
Nama: <?php echo $hasil->id_mhs; ?><br>

<?php endforeach;?>
</p>

</body>
</html>

谁能帮我解决这个无效循环的错误? 谢谢:)

【问题讨论】:

  • var_dump($hasil) 的输出是什么?以及为什么将其保存在变量 $hdcode 中?
  • 那是因为 $profile 是一个字符串,所以将其编码为字符串将解码为字符串,我还注意到您在解码中放入了TRUE。这会将其解码为数组而不是对象

标签: php arrays json parsing object


【解决方案1】:

来自网络服务的响应是 JSON 吗?如果是这样,您不需要对其进行 json_encode。

此外,由于您将 true 作为第二个参数传递给 json_decode,因此它将是一个数组而不是一个对象。你可以打电话

$hasil = json_decode($json_format);

获取一个对象。

同样在你的 foreach 中你需要使用$i 而不是$hasil

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2020-05-02
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多