1

I'm a newbie in PHP so I searched and read a lot of article but can not find any solution in here or somewhere else.My problem is I have a dynamic string like

[{"NAME":"jennifer lopez"},{"Name":"Ricky Martin"}]

or

[{"NAME":"Tom and Jerry"},{"Name":"Donald Duck"},{"Name":"Rick And Morty"}]

it always changes so I want to take only the names like; jennifer lopez Ricky Martin or Tom and Jerry Donald Duck Rick And Morty.I tried

 $pos = strpos($newarray,":")+2;
 $pos1 = strpos($newarray,"}")-1;
 $pos2 = $pos1-$pos;

But it only returns Jennifer Lopez.

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 1
    Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – user3942918 Jul 03 '18 at 09:41
  • I'm not using JSON and I searched all of the topics in here and no one fix my problem like I said above " I searched and read a lot of article but can not find any solution in here or somewhere else" –  Jul 03 '18 at 09:45

2 Answers2

0

If key(which is Name/NAME/name) in the JSON string always changes then the names can be accessed by using the following code.

$x = json_decode('[{"NAME":"jennifer lopez"},{"Name":"Ricky Martin"}]', true);
$names = [];
foreach ($x as $value) {
    $names[] = array_values($value)[0];
}

print_r($names);
Lovepreet Singh
  • 4,792
  • 1
  • 18
  • 36
0

The string you posted seems a JSON format string. If it is a JSON format string, you can use the json_decode($inputString) method to get an array of object.

Additionally, the keys in the JSON string are not the same, as you have posted. If you try to directly access the property with "NAME" or "Name", PHP will reports error/warning. Therefore, you can convert the stdClass object to array and get the first element value. The code looks like:

$inputString = '[{"NAME":"Tom and Jerry"},{"Name":"Donald Duck"},{"Name":"Rick And Morty"}]';

foreach(json_decode($inputString) as $nameObj) {
    $nameArr = (array) $nameObj;
    echo reset($nameArr);
}
swy
  • 46
  • 4