2014-05-16 67 views
0

我想按照'sort' => $date這一行中的時間戳對我的數組進行排序。我試過用array_multisort這樣做,但不能使它工作。目前它只是按照與正常相同的順序打印$data陣列。我在做什麼錯在array_multisort帶時間戳的Array_multisort

我timesmap看起來是這樣的:

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); 
+3

不要用在array_multisort,使用'usort'一點點自定義比較函數。 – CBroe

+0

但是,我首先需要製作一個只有時間戳的新陣列,或者我如何做到這一點。我已經搜索並找到了比較函數 – user3646311

+0

不,您不需要額外的數組 - 您只需讓比較函數從兩個數組元素中選擇特定值作爲參數進行比較即可。 – CBroe

回答

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 
    ) 

)