在multidimentional数组PHP中删除一个数组

时间:2016-06-09 11:58:58

标签: php arrays

我在$data内有一个[23:45]数组,其数组包含useridlogin时间:

$data = array( 
   [93] => array( 
        [23:34] => array(
                [0] => array(
                    [userid]=> 93,
                    [login] =>23:34:03
                ),
                [1] => array(
                    [userid]=> 93,
                    [login] =>23:34:07
                ),
                [2] => array(
                    [userid]=> 93,
                    [login] =>23:34:02
                )
           )
   )

我想要的输出是:

$data = array( 
   [93] => array( 
        [23:45] => array(
                [0] => array(
                    [userid]=> 93,
                    [login] =>23:34:02
                )
           )
       )
)

唯一的左边是最早登录,另一个阵列应该删除。请帮忙

2 个答案:

答案 0 :(得分:1)

找到最短时间:

$earliest = 0;
for ($i = 1; $i < count($data[93]["23:45"]; $i++){
    if (strcmp($data[93]["23:45"][$i]["login"], $data[93]["23:45"][$earliest]["login"]) < 0){
        $earliest = $i;
    }
}

然后用新的数组替换数组,只包含最早的登录名:

$data[93]["23:45"] = array(
    $data[93]["23:45"][$earliest]
);

答案 1 :(得分:1)

首先对数组进行排序,然后排序unset除数组中0索引处的第一项以外的所有项目。

<?php 
$data = array( 
   '93' => array( 
        '23:34' => array(
                0 => array(
                    'userid'=> 93,
                    'login' =>'23:34:03'
                ),
                1 => array(
                    'userid'=> 93,
                    'login' =>'23:34:07'
                ),
                2 => array(
                    'userid'=> 93,
                    'login' =>'23:34:02'
                )
           )
        )
    );

usort($data['93']['23:34'], build_sorter('login'));///sort array    

function build_sorter($key) ///custom sort function just pass the key
{
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}   


foreach($data['93']['23:34'] as $key => $val)
{
    if($key != 0)
    {
        unset($data['93']['23:34'][$key]); ///remove all the items except first item..
    }
}
print_r($data);  
?>

这会给你:

Array
(
    [93] => Array
        (
            [23:34] => Array
                (
                    [0] => Array
                        (
                            [userid] => 93
                            [login] => 23:34:02
                        )

                )

        )

)

现场示例:CLICK HERE