0

i have this JSON

[
{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}
]

I want to get only those with this ID 2513

[
{"name":"Maria";"Sex":"Female","ID":"2513"}
]
Rob
  • 14,746
  • 28
  • 47
  • 65

2 Answers2

3

Your JSON String is invalid. First replace all the semicolons ; with comma , and then try using array_filter() or any other way e.g foreach() with if condition etc. I've used the array_filter() way, hope it helps :)

<?php
$json = '[{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria","Sex":"Female","ID":"2513"},{"name":"Pedro","Sex":"Male","ID":"2211"}]';
$array = json_decode($json,1);
$ID = 2513;
$expected = array_filter($array, function ($var) use ($ID) {
    return ($var['ID'] == $ID);
});
print_r($expected);
?>

DEMO: https://3v4l.org/kZrMo

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

Use json_decode() to convert the JSONString to a PHP array of objects

$str = '[{"name":"Juan","Sex":"Male","ID":"1100"},"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}]';

$arr = json_decode($str);

foreach ( $arr as $obj ){
    if ( $obj->ID == 2513 ) {
        echo $obj->name;
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149