-1

I need to loop through some JSON and get the Ids

Here is my JSON

{"Master":123456,"Ids":[1,3,8]}

I need to get all of the Ids and add a prefix .pre- so I end up with this in PHP:

$Ids =  ".pre-1, .pre-3, .pre-8"

Any help with this is very much appreciated. I did look through other posts and tried some things but I couldn't do it.

Thanks

Cybercampbell
  • 2,486
  • 11
  • 48
  • 75
  • Lets see how you have tried to do this – RiggsFolly May 07 '16 at 15:44
  • I tried the answer in this post: https://stackoverflow.com/questions/4343596/parsing-json-file-with-php?rq=1 – Cybercampbell May 07 '16 at 15:45
  • Hint: [json_decode()](http://php.net/manual/en/function.json-decode.php), [array_walk](http://php.net/manual/en/function.array-walk.php), and then [implode()](http://php.net/manual/en/function.implode.php). – Rajdeep Paul May 07 '16 at 15:52

1 Answers1

1

Just do these:

$json = '{"Master":123456,"Ids":[1,3,8]}';

$arr = json_decode($json);

$arr2 = array();
foreach($arr->Ids as $val){
    $arr2[] = ".pre-".$val;
}

echo $Ids = '"'.implode(", ", $arr2).'"'; //".pre-1, .pre-3, .pre-8"
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42