简体   繁体   中英

Find entries with min and max column value and print multiple values

I want to get the "created-at" data according to the min and max values I get. I have a JSON which is something like this.

{
    "channel": {
        "id": "xxxxxxx",
        "field1": "A",
        "created_at": "2021-06-16T19:06:15+07:00",
        "updated_at": "2021-06-16T19:09:58+07:00",
        "last_entry_id": 459
    },
    "feeds": [
        {
            "created_at": "2021-06-19T07:00:11+07:00",
            "entry_id": 1,
            "field1": "26.51"
        },
        {
            "created_at": "2021-06-19T07:00:26+07:00",
            "entry_id": 2,
            "field1": "26.78"
        },
        {
            "created_at": "2021-06-19T07:00:56+07:00",
            "entry_id": 3,
            "field1": "26.81"
        }
    ]
}

and this is my code.

$url = 'https://zzz';

$sumber = file_get_contents($url);
$z = json_decode($sumber);

print_r($z);
echo '<br><br>';

$length = count($z->feeds);

$val1 = array();

for ($i = 0; $i < $length; $i++) {
    $val1[] = round($z->feeds[$i]->field1, 2);
}       

$min1 = min($val1);
$max1 = max($val1);

echo "max : ". $max1 ." - min: ". $min1.'<br>';

The result of my code above is like this max : 26.81 - min: 26.51

, but I want the result like this max : 26.81 2021-06-19T07:00:56+07:00 - min: 26.51 2021-06-19T07:00:11+07:00

Can anyone help me?

Sort the feeds array by the field1 column, then (assuming at least 1 entry in the feeds array and with no respect for "ties") access the first and last entry.

Use printf() to cleanly display the data without messy concatenation.

Code: ( Demo )

$feeds = json_decode($json, true)['feeds'];

usort($feeds, function($a, $b) {
    return $b['field1'] <=> $a['field1'];
});

$last = array_slice($feeds, -1)[0];

printf(
    'max : %.2f %s - min: %.2f %s',
    round($feeds[0]['field1'], 2),
    $feeds[0]['created_at'],
    round($last['field1'], 2),
    $last['created_at']
);

Output:

max : 26.81 2021-06-19T07:00:56+07:00 - min: 26.51 2021-06-19T07:00:11+07:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM