1

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.

3
  • Is that your code? If so, your JSON string is badly escaped. Commented Nov 21, 2013 at 8:59
  • @Florent, His JSON is good. Commented Nov 21, 2013 at 9:00
  • @ShankarDamodaran You know what I mean (see your answer). Commented Nov 21, 2013 at 9:02

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answers Shankar and Deepu. I've simplified here my code to focus in the problem and I've had a couple of errors, the jsonString is readed from sql it's not a fixed local var like the example, then I don't have the quote errors and semicolons. But your answers helped me a lot, I've had wrong the loop and I've had a wrong echo that spoiled the outpout. Thanks a lot!
(I've voted up offcourse, I don't know anything about the downvote)
1

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

Comments

1
$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.