二维数组中,如下:
$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
$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
$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'];
//不用循环
<?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'];
}
}?>
代码更改如下即可:
<?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'是区分大小写的
能不能不用循环的思路,得到 thisUrl为a.php的记录呢,thanks
'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);