C
C
cm_platon2016-05-20 20:41:17
PHP
cm_platon, 2016-05-20 20:41:17

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" }
]

I translate everything into a PHP array (json_decode). Now the question itself. How to make the output of the values ​​of the resulting array like this:
  1. the function iterates through the array and compares the value of the "lastName" element with the given pattern (for example, "Doe")
  2. further, if there are matches, then selects only one element (which has the smallest value in "birth")
  3. outputs that single element

That is, from the entire array (above), only this element will be displayed:
[
    { "firstName": "John",  "lastName": "Doe", "birth": "1987-01-01" }
]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
titronfan, 2016-05-20
@cm_platon

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]);
?>

X
xmoonlight, 2016-05-20
@xmoonlight

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.

A
Anatoliy Lyovkin, 2016-05-20
@Alyovkin

/**
 * 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'));

b63a1f4ee20843eba6347377174a4186.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question