2015-10-28 131 views
-2

我見過幾個類似主題的問題,但其中大多數使用arrays[1, 2, 3, 4, 5]進行排序,而不是我需要使用的是[1, 1, 2, 1, 4],與最大的數字排在第一位,零點被刪除。排序陣列重複值的另一個陣列

示例: [4, 3, 8, 0, 0]作爲要排序的數組和["hello", "my", "name", "is", "indigo"]作爲要排序的數組。 這應該變成: ["name", "hello", "my"] 因爲零被刪除。

我的主要問題是,我試過的大多數方法最終將一個數組中的值分配給另一個數組中的數值。例如:

[4, 1, 1, 4, 8]["hello", "my", "name", "is", "indigo"]

應該返回["indigo", "is", "hello", "my", "name"],但返回["indigo", "hello", "hello", "my", "my"],或諸如此類的話。

+0

使用php數組** sort()**函數 –

+0

rsort()和array_filter()? –

+0

嘗試自己的事情,讓我們知道。 –

回答

0

要使用rsort()

解決方案

$arrayVariable = array(1, 1, 2, 1, 4); 

rsort($arrayVariable); 

這裏手動rsort()

+0

你誤解了我的問題。我已經編輯它使其更容易理解,但您可能想要刪除此問題。 – Hate9

1

我認爲你正在尋找這樣的事情?

$words = array("hello", "my", "name", "is", "indigo"); 
$order = array(0, 1, 3, 2, 4); 
$result = array_map(function($o) use ($words){ 
    return $words[$o]; 
}, $order); 

將會產生這樣的:

array(5) { 
    [0] = string(5) "hello" 
    [1] = string(2) "my" 
    [2] = string(2) "is" 
    [3] = string(4) "name" 
    [4] = string(6) "indigo" 
} 

更新

我已經重讀你的問題,但我仍然不能確定你追求什麼? 我已經更新了我的原始代碼,但是現在刪除了0,並將最大的數字排序爲最小。儘管如果0被刪除,你不能訪問數組的第一個元素?

如果這是不正確的,也許你可以解釋它做錯了什麼,它需要做什麼不同。我懷疑這個問題只是語言故障。

$words = array("hello", "my", "name", "is", "indigo"); 
$order = array(0, 0, 4, 4, 3, 1); 

$order = array_filter($order); // remove 0's 
rsort($order);     // Largest First 
$result = array_map(function($o) use ($words){ 
    return $words[$o]; 
}, $order); 

將會產生這樣的:

array(4) { 
    [0] = string(6) "indigo" 
    [1] = string(6) "indigo" 
    [2] = string(2) "is" 
    [3] = string(2) "my" 
} 
+0

這實際上幾乎可行,但它將'[0,0,4,4]'+'[「text1」,「text2」,「text3」,「text4」]分配爲'[「text1」,「 text1「,」text3「,」text3「]' – Hate9

+0

@ Hate9這正是我以爲你想要的?如果不是,你需要詳細說明。 – Christian

+0

我的第一個問題太含糊,但我編輯它以使其更有意義。 – Hate9

0

更新

我終於想通了,什麼是錯的我在做什麼,並固定它。對於任何人誰是好奇什麼,我試圖做(因爲我顯然它拉屎),或如何我最終做到了,這裏是我的代碼:

$words=array("hello","my","name","is","indigo"); 
$sort=array(4,3,8,0,0); 
$count=0; 
foreach($sort as $item){ 
    if ($item==0) { 
     $count++; 
    } 
} 
$cut=count($sort)-$count; 
for($i=count($sort); $i>=$cut; $i--) { 
    unset($sort[$i]); 
    unset($words[$i]); 
} 
array_multisort($sort,$words); 
$words=array_reverse($words); 
foreach($words as $word){ 
    echo $word."<br>"; 
} 

,輸出:

name 
hello 
my