I have an array(s) below that are coming from an API I'm working with that I've drilled down to get too, I need to select the one with the biggest filesize and then display all that information. I'm not really understanding some of the other suggestions I've seen here, so I was wondering if somebody could point me in a direction.
Array
(
[type] => video/mp4
[height] => 180
[width] => 320
[label] => H.264 320px
[filesize] => 257228869
)
Array
(
[type] => video/mp4
[height] => 270
[width] => 480
[label] => H.264 480px
[filesize] => 371518109
)
Array
(
[type] => video/mp4
[height] => 406
[width] => 720
[label] => H.264 720px
[filesize] => 494828944
)
Array
(
[type] => video/mp4
[height] => 720
[width] => 1280
[label] => H.264 1280px
[filesize] => 1042311723
)
Here's my code to show how I've gotten the above
//Initiate cURL.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$json = json_decode($result, TRUE);
$videoids = $json['media'];
foreach ($videoids as $videoid) {
//Initiate cURL.
$ch = curl_init($url3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Execute the request
$result = curl_exec($ch);
$json = json_decode($result, TRUE);
$playlists = $json['playlist'];
foreach ($playlists as $playlist) {
$sources = $playlist['sources'];
foreach ($sources as $source) {
if ($source['type'] == "video/mp4") {
echo "<pre>";
print_r($source);
echo "</pre>";
}
}
echo "<br>";
}
}
-
Did you give up?AbraCadaver– AbraCadaver2021年05月28日 13:39:21 +00:00Commented May 28, 2021 at 13:39
3 Answers 3
I would probably sort, but for fun; extract the filesize
columns, get the max
and search for it in the original array:
$sizes = array_column($array, 'filesize');
$result = $array[array_search(max($sizes), $sizes)];
A sort option:
array_multisort(array_column($array, 'filesize'), SORT_DESC, $array);
$result = $array[0];
Or omit the SORT_DESC
to get ascending (if you need that for something) and then:
$result = end($array);
You can sort your array and then just take the first one:
$array = array(
array(
"filesize" => 1234,
"title" => "item1"
),
array(
"filesize" => 12345,
"title" => "item2"
),
array(
"filesize" => 12346,
"title" => "item3"
)
);
$bsize=0;
uasort($array, function ($a, $b) {
return ($b['filesize'] - $a['filesize']) ;
});
// biggest is $array[0]
I generally like array_reduce. It's simple and clean...
$bigplay = array_reduce($playlists, function($c, $it) {
if (!$c || $it['filesize'] > $c['filesize'])
$c = $it;
return $c; }, []);
$bigplay will have the information about the entry with the biggest filesize (or an empty array if there were no playlists).