从php解码javascript json时出错

时间:2013-11-21 08:54:27

标签: php json

我在使用javascript JSON.stringfy创建的json解码时遇到问题。也许问题是对象有数组。 JSON和核心是:

$jsonString = "{"tabLabels":["tab1","tab2","tab3","tab4","tab5"],"tabBgs":["21","2","3","0","4"],"tabPublico":[0,0,1,1,0],"fuente":"2","size":"17px"}";

$jsonObj = json_decode($jsonString);

echo $jsonObj->obj;
$tabs = $jsonObj->tabPublico
for ($i=0;$i<strlen($tabs);$i++)
{
   echo $tabs[i];
}

“回声”没有显示任何内容。

感谢您的帮助。 奥斯卡。

3 个答案:

答案 0 :(得分:1)

这些是你的错误。

  • 使用单引号
  • 附上 $jsonString
  • 您在第6行错过了分号 ;
  • 您使用 strlen() 代替 count()

修改后的代码。

<?php
$jsonString = '{"tabLabels":["tab1","tab2","tab3","tab4","tab5"],"tabBgs":["21","2","3","0","4"],"tabPublico":[0,0,1,1,0],"fuente":"2","size":"17px"}';

$jsonObj = json_decode($jsonString);
$tabs = $jsonObj->tabPublico;
foreach($tabs as $k=>$v)
{
echo $v;
}

<强>输出:

00110

答案 1 :(得分:1)

尝试这样。你的json被严重转义,对于一个数组,你必须使用count()来找到要循环的数组的长度。

$jsonString = '{"tabLabels":["tab1","tab2","tab3","tab4","tab5"],"tabBgs":["21","2","3","0","4"],"tabPublico":[0,0,1,1,0],"fuente":"2","size":"17px"}';
$jsonObj = json_decode($jsonString);
$tabs = $jsonObj->tabPublico;
for($i=0;$i<count($tabs);$i++)
{
   echo $tabs[$i];
}

答案 2 :(得分:1)

$jsonString = '{"tabLabels":["tab1","tab2","tab3","tab4","tab5"],"tabBgs":["21","2","3","0","4"],"tabPublico":[0,0,1,1,0],"fuente":"2","size":"17px"}'

在单引号下传递JSON字符串。