【问题标题】:Minimum value in each row of the array [duplicate]数组每一行的最小值[重复]
【发布时间】:2013-10-13 21:26:47
【问题描述】:

我试图从列名中包含“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";
}
?>

【问题讨论】:

  • @Jon,你能告诉我什么吗?
  • 在说它是重复的问题之前,请仔细阅读问题
  • @AbdulRahim:不,但是如果您去阅读手册,则可以。在不了解代码的作用的情况下使用代码不会帮助您学习。

标签: php


【解决方案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";
}
?>

strstr()代替strpos()

【讨论】:

  • 亲爱的阿吉斯,非常感谢。完美运行
猜你喜欢
  • 2022-06-28
  • 1970-01-01
  • 2012-05-07
  • 2022-12-12
  • 2019-11-20
  • 1970-01-01
  • 2015-07-12
  • 2019-02-08
  • 2016-04-13
相关资源
最近更新 更多