我试图从任意列中获取最小值,在列名中包含“xx”。我认为列名称中存在问题可能是因为它们以数字开头。
以下是我的代码:
<?php
$array = array(
array(
'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'xx') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n";
}
?>
答案 0 :(得分:1)
这是工作代码,
<?php
$array = array(
array(
'id' => 1,
'10xx' => 14,
'11xx' => 32,
'12xx' => 4
),
array(
'id' => 2,
'10xx' => 13,
'11xx' => 36,
'12xx' => 41
)
);
foreach ($array as $item) {
$lowestKey = '';
foreach ($item as $key => $value) {
if (strstr($key, 'xx')) {
if ($lowestKey == '') {
$lowestKey = $key;
} else {
if ($value < $item[$lowestKey]) {
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey] . "\n";
}
?>
而不是strpos()
使用strstr()