0

Following code is giving an array with json objects. But I need json string of that array so that I can use json_decode later. How to do it?

for($i=0;$i<5;$i++)
{   foreach($allGames as $game)
    {   if($game['desc']==$sortGames[$i])
        {   $text[$i]=array('Game_name'=>$game['desc'],'GameId'=>$game['gameId'],'order'=>$goalids,'length'=>$game['length']);
            break;
        }
    }
}
$json_string=json_encode($text);

the value of $json_string is as following:

[{"Game_name":"a","GameId":"1697","order":["11022","11021","11020","11024","11023"],"length":"2.08783938975344"},{"Game_name":"b","GameId":"1800","order":["12196","12197","12194","12195","12193","12198"],"length":"1.16970835124072"}]
9
  • what do u mean json string of array? in the result you get string already Commented Mar 9, 2017 at 13:48
  • The result is json array. json_decode is unable to decode it. Commented Mar 9, 2017 at 13:55
  • so the problem is you can't decode encoded string? Commented Mar 9, 2017 at 13:58
  • yes @bxN5 that is the problem Commented Mar 9, 2017 at 14:55
  • your json is correct sandbox.onlinephpfunctions.com/code/… Commented Mar 9, 2017 at 15:03

1 Answer 1

1
for($i=0;$i<5;$i++)
{   foreach($allGames as $game)
    {   if($game['desc']==$sortGames[$i])
        {   $text[$i]=(array('Game_name'=>$game['desc'],'GameId'=>$game['gameId'],'order'=>json_decode($goalids),'length'=>$game['length']));
            break;
        }
    }
}
$json_string=json_encode($text);
Sign up to request clarification or add additional context in comments.

6 Comments

what is the difference?
Ok, it is fixing my problem but it is creating the order as null.
I made my code as: for($i=0;$i<5;$i++) { foreach($allGames as $game) { if($game['desc']==$sortGames[$i]) { $text[$i]=(array('Game_name'=>$game['desc'],'GameId'=>$game['gameId'],'order'=>json_decode($goalids),'length'=>$game['length'])); break; } } } $json_string=json_encode($text); $test=json_decode($json_string,true); var_dump($test);
and the result is array(5) { [0]=> array(4) { ["Game_name"]=> string(1) "1" ["GameId"]=> string(2) "57" ["order"]=> NULL ["length"]=> string(2) "10" } [1]=> .... and so on.. }
still null using htmlentities.. the error is : PHP Warning: htmlentities() expects parameter 1 to be string, array given
|

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.