-1

In mooodle I create a course via web service the output of array that I print via command print_r is:

 [{"id":29,"shortname":"math1"}]

I wanna to extract just 29 of this text via PHP how can id do it?

melody
  • 15
  • 2

1 Answers1

0

to do this you have to decode the array:

<?php

$json_array = ' [{"id":29,"shortname":"math1"}]';
$php_array = json_decode($json_array);
echo $php_array[0]->id;

And you can do a foreach loop if there is more data

Sandbox link

Burhan Kashour
  • 674
  • 5
  • 15
  • Its worth noting that if the string fails to decode, this will produce an error. It might be better to protect against that. – Wesley Smith Nov 15 '20 at 07:56
  • @WesleySmith True, he must check the array before echo or print, he know the logic now, its better to use `foreach` instead of using `[0]` and must check for empty or null array – Burhan Kashour Nov 15 '20 at 09:17