我有以下陣列
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
我想從上面的陣列中得到快樂的陣列中的最高價格名稱 car 的鍵。有兩個提示有問題:
- 如果 $data 變數的值為空,則函式必須回傳空值。
2. getHighestPrice 函式應該沒有引數。代碼的一般視圖如下:
<?php
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
,
// ...
];
function getHighestPrice()
{
// TODO: Implement
}
感謝您提前提供幫助。
uj5u.com熱心網友回復:
您可以使用array_column從“價格”中獲取一維陣列。php 然后具有最大值的函式max()。
$maxPrice = max(array_column($data,'price'));
函式的定義只有在它也使用引數時才有意義。如果沒有引數,您將不得不使用全域變數,但 PHP 中沒有人不這樣做。
function getHighestPrice($data,$name){
$prices = array_column($data,$name);
return $prices == [] ? NULL : max($prices);
}
$maxPrice = getHighestPrice($data,'price');
如果陣列 $data 為空或名稱不作為列存在,則該函式回傳 NULL。
在3v4l.org上嘗試自我
uj5u.com熱心網友回復:
根據您的要求,如果getHighestPrice()函式應該沒有引數,那么您必須$data從全域范圍獲取。
<?php
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
function getHighestPrice()
{
$data = $GLOBALS['data'] ?? null;// Get $data variable
if(empty($data)){
return null;// If empty then return null
}
// Sorting
usort($data, function($a, $b) {
return $a['price'] < $b['price'];
});
// Return the maximum price
return $data[0]['price'];
// Return the car name of maximum price
/*
return $data[0]['name'];
*/
}
echo getHighestPrice();
輸出:15218
uj5u.com熱心網友回復:
我想你想要最高價值的鑰匙
$data = [
[
'name' => 'Electric Khodro',
'price' => 12912
],
[
'name' => 'Iran Khodro',
'price' => 15218
],
[
'name' => 'Iran arghaam',
'price' => 8853
]
];
echo(getHighestPrice($data));
function getHighestPrice($array = [])
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value['price'] > $max) {
$result = $key;
$max = $value['price'];
}
}
return $result;
}
輸出:
1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436816.html
