带有时间戳的Array_multisort

时间:2014-05-16 22:18:46

标签: php sorting

我正在尝试按照此行'sort' => $date中的时间戳对数组进行排序。我已尝试使用array_multisort,但无法使其正常工作。目前它只是以与正常相同的顺序打印$data数组。我在array_multisort做错了什么?

我的时间图如下所示:

1397755920

这是我的代码:

$data = array();
for ($x=0; $x<=count($obj)-1; $x++) {
$date = strtotime(str_replace('/', '-', $obj[$x]['time']));
    $post_data = array(
    'title' => $obj[$x]['title'],
    'link' => $obj[$x]['link'],
    'image' => $obj[$x]['image'],
    'content' => $obj[$x]['content'],
    'time' => $obj[$x]['time'],
    'sort' => $date,
    'name' => $obj[$x]['name']);
     $data[] = $post_data;
}

array_multisort($data['sort'], SORT_DESC);
print_r($data);

USORT示例:

function my_sort($a,$b)
{
    if ($a==$b) return 0;
        return ($a<$b)?-1:1;
    }

for ($x=0; $x<=count($data)-1; $x++) {

    usort($data[$x]['sort'],"my_sort");

}
print_r($data);

1 个答案:

答案 0 :(得分:0)

或者,是的,你可以在这个中使用array_multisort()。在上一个示例中,您忘记提供包含时间戳的另一个数组。考虑这个例子:

// dummy data
$sample_timestamp = 1397755920;
$obj = array(
    array(
        'title' => 'title1',
        'link' => 'link1',
        'image' => 'image1',
        'content' => 'content1',
        'sort' => $sample_timestamp,
    ),
    array(
        'title' => 'title2',
        'link' => 'link2',
        'image' => 'image2',
        'content' => 'content2',
        'sort' => 1000,
    ),
    array(
        'title' => 'title3',
        'link' => 'link3',
        'image' => 'image3',
        'content' => 'content3',
        'sort' => $sample_timestamp+100,
    ),
);

$data = $timestamps = $post_data = array();
for($x = 0; $x < count($obj); $x++) {
    $timestamps[] = $obj[$x]['sort']; // you forgot to add another array
    $post_data = array(
        'title' => $obj[$x]['title'],
        'link' => $obj[$x]['link'],
        'image' => $obj[$x]['image'],
        'content' => $obj[$x]['content'],
        'sort' => $obj[$x]['sort']);
    $data[] = $post_data;
}

array_multisort($timestamps, SORT_DESC, $data);


print_r($data);

示例输出:

Array
(
    [0] => Array
    (
        [title] => title3
        [link] => link3
        [image] => image3
        [content] => content3
        [sort] => 1397756020
    )

    [1] => Array
    (
        [title] => title1
        [link] => link1
        [image] => image1
        [content] => content1
        [sort] => 1397755920
    )

    [2] => Array
    (
        [title] => title2
        [link] => link2
        [image] => image2
        [content] => content2
        [sort] => 1000
    )

)