我如何在多维数组中确定最近一年的一年,并使用它仅在一个数组中访问CodeIgniter中的元素



预先感谢。我正在研究一个小型Codeigniter应用程序,在该应用程序中,我正在尝试从多维阵列中获得最新的捐赠。以下是数组的部分var_dump:

 <?php
  array (size=8)
  0 =>
    array (size=19)
      'id' => string '36' (length=2)
      'date' => string '2013-01-09 00:00:00' (length=19)
      'year' => string '2008' (length=4)
      'acc_no' => string '550120' (length=6)
      'name' => string 'Johanson' (length=4)
      'bbf' => string '' (length=0)
      'jan_amount' => string '50' (length=0)
      'feb_amount' => string '100' (length=0)
      'mar_amount' => string '' (length=0)
      'apr_amount' => string '60' (length=2)
  1 =>
    array (size=19)
      'id' => string '43' (length=2)
      'date' => string '2013-01-09 00:00:00' (length=19)
      'year' => string '2009' (length=4)
      'acc_no' => string '550120' (length=6)
      'name' => string 'Johanson' (length=4)
      'bbf' => string '90' (length=2)
      'jan_amount' => string '' (length=0)
      'feb_amount' => string '120' (length=0)
      'mar_amount' => string '' (length=0)
      'apr_amount' => string '140' (length=3)
  2 =>
    array (size=19)
      'id' => string '51' (length=2)
      'date' => string '2013-01-09 00:00:00' (length=19)
      'year' => string '2010' (length=4)
      'acc_no' => string '550120' (length=6)
      'name' => string 'Johanson' (length=4)
      'bbf' => string '' (length=0)
      'jan_amount' => string '' (length=0)
      'feb_amount' => string '250' (length=0)
      'mar_amount' => string '' (length=0)
      'apr_amount' => string '30' (length=0)

?>

我想做的:

我想确定最新一年(在示例2010年 - 是第三个数组中的最大数字),一旦我这样做,就为数组中的所有元素创建变量。然后,我想在页面下使用变量。因此,当添加一年的数据库时,如果是最新的,则该系统应在当年选择。

我到目前为止所做的事情:我已经在一维数组上成功完成了这种事情,所以我正在绊倒这个!我已经成功使用了内置的in_array函数来查找数组中的内容以及Max()从其访问其他元素中获取最高数字。我还想到使用从低到高的排序,然后使用end()函数,但是我无法在这样的多维数组上这样做。

任何帮助将不胜感激。

获得数组的简单解决方案是:

$index = null;
$year = 0;
foreach( $data as $key => $row ){
    if( $row['year'] > $year){
       $index = $key;
    } 
    $year = $row['year'];
}
// to extract variables from their array containers, you can use the function 'extract', note however, that whenever you use extract, it will try to overwrite the previously declared variable's name!!
extract($data[$index]);
// now you can use $year
echo "the latest year is " . $year;

最新更新