Oscardrbcn
Oscardrbcn

Reputation: 688

Error decoding a javascript json from php

I'm having problems decoding from php a json created with javascript JSON.stringfy. Maybe the problem is that the object has arrays. The JSON and the core are:

$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];
}

The "echoes" don't show anything.

Thank you for your help. Oscar.

Upvotes: 1

Views: 86

Answers (3)

These were your mistakes.

  • Enclose your $jsonString with single quote
  • You missed a semicolon ; on the 6th line.
  • You are using strlen() instead of count().

Modified code.

<?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;
}

OUTPUT:

00110

Upvotes: 1

Surabhil Sergy
Surabhil Sergy

Reputation: 2006

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

pass JSON string under single quotes.

Upvotes: 1

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Try like this.You json was badly escaped and for an array you must use count() to find the length of array to loop through.

$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];
}

Upvotes: 1

Related Questions