weixin_33749131 2017-07-24 08:29 采纳率: 0%
浏览 24

JSON解码错误

I am sending php array as json format, but I was unable to decode the value. Here is how I made the array

    $ads = $atts['ads'];
    if (sizeof($ads) > 0) {
    foreach($ads as $social_item) {
        $sdbr = $social_item['sidebar'];
        $pno = $social_item['no'];
        $out[$sdbr] = $pno;
    }
}

Which output

array (
  'Full width ad 1' => 2,
  'sidebar-1' => 3,
)

Now I have json encode it

$myJSON = json_encode($out);

The json formatted value {"Full width ad 1":2,"sidebar-1":3} Then I am passing it through data attribute value

echo "<div data-ad = '$myJSON' class='ash_loadmore'><span>LOAD MORE</span>
</div>";

The out that I have got

$ad = $_POST['ad'];
array (
  'Full width ad 1' => '2',
  'sidebar-1' => '3',
)

So now time for decode the output

    $out = json_decode($ad,TRUE);
    var_dump($out); // Returns NULL although the array value is present

But if I put the json format data it works fine

    $out = json_decode('{"Full width ad 1":2,"sidebar-1":3}',TRUE);
    var_dump($out);

I suspect before json encode the array array(2) { ["Full width ad 1"]=> int(2) ["sidebar-1"]=> int(3) } value is int but I am getting value as string array(2) { ["Full width ad 1"]=> string(1) "2" ["sidebar-1"]=> string(1) "3" }

What's wrong doing by me?

  • 写回答

2条回答 默认 最新

  • weixin_33725722 2017-07-24 08:33
    关注

    After this step:

    $ad = $_POST['ad'];
    array (
      'Full width ad 1' => '2',
      'sidebar-1' => '3',
    )
    

    you see in the output that this is already a php array, so any json-decode method will fail (this is no json).

    You can work with the array right away, depending what you want to do ;)

    评论

报告相同问题?