Answer the question
In order to leave comments, you need to log in
How to sort and filter a JSON array according to a given pattern?
Good day!
There is JSON:
[
{ "firstName": "John", "lastName": "Doe", "birth": "1987-01-01" },
{ "firstName": "Anna", "lastName": "Smith", "birth": "1999-03-03" },
{ "firstName": "Peter", "lastName": "Doe", "birth": "1989-02-02" },
{ "firstName": "Al", "lastName": "Sums", "birth": "1980-04-04" }
]
[
{ "firstName": "John", "lastName": "Doe", "birth": "1987-01-01" }
]
Answer the question
In order to leave comments, you need to log in
Sorry for the bad code. It seems to work.
<?
$str = '[
{ "firstName": "John", "lastName": "Doe", "birth": "1987-01-01" },
{ "firstName": "Anna", "lastName": "Doe", "birth": "1999-03-03" },
{ "firstName": "Peter", "lastName": "Doe", "birth": "1989-02-02" },
{ "firstName": "Al", "lastName": "Sums", "birth": "1980-04-04" }
]';
$arr = json_decode($str);
$arr_search = array();
$count = 0;
foreach ($arr as $key => $value) {
if ($value->lastName == 'Doe') {
$arr_search[$count] = $value->birth;
}
$count++;
}
asort($arr_search);
$first_key = key($arr_search);
var_dump($arr[$first_key]);
?>
Paradox! Where the world is heading)
You need to work with data sampling / sorting at the database level!
Inside PHP - only manipulation with them and preparation of content for output.
/**
* Sort data (for fun)
*
* @param array|string $input
* @param string $pattern
* @return array
*/
function search($input, $pattern) {
if (is_string($input))
$input = json_decode($input);
$clean = [];
foreach($input as $item) {
if($item->lastName == $pattern) {
$clean[] = $item;
}
}
if(count($clean) > 1)
foreach($clean as $key => $value) {
$cmpDate[$key] = date($value->birth);
}
$clean[] = array_multisort($cmpDate, SORT_ASC, $clean);
return array_values($clean)[0];
}
var_dump(search($json, 'Doe'));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question