二维数组中,如下:
$arr = array (  
'0' => array ( 'userId' => 1,'thisUrl' => 'a.php', 'dateTime' => '2010-11-17 14:48:30' ),  
'1' => array ( 'userId' => 2,'thisUrl' => 'b.php', 'dateTime' => '2010-11-17 14:42:57' ),  
'5' => array ( 'userId' => 6,'thisUrl' => 'e.php', 'dateTime' => '2010-11-18 15:02:25')  
);
现:要得到userId为1的dataTime
方法一:
foreach($arr as $a=>$r)

  if($r['userId']==1)
  { 
    echo $r['dateTime'];
  } 
}
方法一中用的是循环,如果二维数组记录很多时,效率会很低,
问:还有其它的更好的方法可得到userId为1的dataTime吗,thanks

解决方案 »

  1.   

    我个人觉得你的外层key可以设置为userId,这样就好了
    $arr = array (   
    1 => array ( 'userId' => 1,'thisUrl' => 'a.php', 'dateTime' => '2010-11-17 14:48:30' ),   
    2 => array ( 'userId' => 2,'thisUrl' => 'b.php', 'dateTime' => '2010-11-17 14:42:57' ),   
    6 => array ( 'userId' => 6,'thisUrl' => 'e.php', 'dateTime' => '2010-11-18 15:02:25')   
    );echo $arr[$userID]['dateTime'];
    //不用循环
      

  2.   

    多谢二楼的,那如果要得到 thisUrl为a.php的记录呢,
      

  3.   

    对于数组一般来说使用内置函数比较快一些,代码更改如下:
    <?php
    /* 
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    $arr = array (
    '0' => array ( 'userId' => 1,'thisUrl' => 'a.php', 'dateTime' => '2010-11-17 14:48:30' ),
    '1' => array ( 'userId' => 2,'thisUrl' => 'b.php', 'dateTime' => '2010-11-17 14:42:57' ),
    '5' => array ( 'userId' => 6,'thisUrl' => 'e.php', 'dateTime' => '2010-11-18 15:02:25')
    );
    foreach($arr as $a=>$r)
    {
      if(array_search('1', $r)=='userId')
      {
      echo $r['dateTime'];
      }
    }?>
      

  4.   


    代码更改如下即可:
    <?php
    /* 
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    $arr = array (
    '0' => array ( 'userId' => 1,'thisUrl' => 'a.php', 'dateTime' => '2010-11-17 14:48:30' ),
    '1' => array ( 'userId' => 2,'thisUrl' => 'b.php', 'dateTime' => '2010-11-17 14:42:57' ),
    '5' => array ( 'userId' => 6,'thisUrl' => 'e.php', 'dateTime' => '2010-11-18 15:02:25')
    );
    foreach($arr as $a=>$r)
    {
      if(array_search('a.php', $r)=='thisUrl')
      {
      echo $r['dateTime'];
      }
    }?>注意'a.php'是区分大小写的
      

  5.   

    多谢
    能不能不用循环的思路,得到 thisUrl为a.php的记录呢,thanks
      

  6.   

    $arr = array (   
    '0' => array ( 'userId' => 1,'thisUrl' => 'a.php', 'dateTime' => '2010-11-17 14:48:30' ),   
    '1' => array ( 'userId' => 2,'thisUrl' => 'b.php', 'dateTime' => '2010-11-17 14:42:57' ),   
    '5' => array ( 'userId' => 6,'thisUrl' => 'a.php', 'dateTime' => '2010-11-18 15:02:25')   
    );$key = 'thisUrl';
    $value = 'a.php';
    $t = array_filter($arr, create_function('$s', "return \$s['$key']=='$value';"));print_r($t);