请考虑以下内容:
$characterStats = [
['strength' => 500],
['dexterity' => 200],
['agility' => 1000],
['intelligence' => 1200],
['health' => 675],
];
$stat = array_search(max($characterStats), $characterStats);
echo $stat;
['intelligence' => 1200]
有人可以帮助我实现我想要的吗?
答案 0 :(得分:1)
请尝试以下操作:
$characterStats = array(
'strength' => 500,
'dexterity' => 200,
'agility' => 1000,
'intelligence' => 1200,
'health' => 675,
);
$stat = array_search(max($characterStats), $characterStats);
echo $stat;
我更改了声明数组的方式。我相信,如果通过以下调用使用嵌套数组,则可能需要指明要搜索的字段名称:
$stat = array_search(max($characterStats), array_column($characterStats, 'KEYNAME'));
但是,由于每个子数组只有1个具有不同“键”的元素,因此它并不是最佳方法。对于您的方案,您可能需要使用另一种方法,即遍历每个元素并存储找到的最大值。
答案 1 :(得分:1)
使用当前的数组,这是我想到的最简单的方法,将其作为标准的foreach()
并保留最大值和找到元素的位置(保存另一个搜索以获取完整的条目)...
$characterStats = [
['strength' => 500],
['dexterity' => 200],
['agility' => 1000],
['intelligence' => 1200],
['health' => 675],
];
$maxStat = null;
$max = null;
foreach ( $characterStats as $stat ){
if ( current($stat) > $max ) {
$max = current($stat);
$maxStat = $stat;
}
}
print_r( $maxStat);