2016-08-02 41 views
0

合并多维数组我有这样的数组:PHP,排序/其他(较小)阵列

$original=[]; 
$original[]=['value'=>'a','count'=>10]; 
$original[]=['value'=>'b','count'=>15]; 
$original[]=['value'=>'c','count'=>23]; 
$original[]=['value'=>'d','count'=>40]; 
$original[]=['value'=>'e','count'=>25]; 

而这个数组包含应在$原始数组开头的项目:

$sort=['d','c']; 

所以结果最终应:

[ 
    (int) 0 => [ 
     'value' => 'd', 
     'count' => (int) 40 
    ], 
    (int) 1 => [ 
     'value' => 'c', 
     'count' => (int) 23 
    ], 
    (int) 2 => [ 
     'value' => 'a', 
     'count' => (int) 10 
    ], 
    (int) 3 => [ 
     'value' => 'b', 
     'count' => (int) 15 
    ], 
    (int) 4 => [ 
     'value' => 'e', 
     'count' => (int) 25 
    ], 
] 

使用一个简单的循环,这是可行的,但有一个很好的方式, 去做这个?

+0

是您的'$ sort'阵列应该是多维的?例如对于'$ sort = [['d','c'],['b','a']]'',您期望什么样的行为? – wazelin

+0

No. $ sort只包含值键,没有别的 –

+0

但在你的例子中它是'$ sort = [['d','c']]''。 – wazelin

回答

0

你可以做到这一点使用usort

$priority = ['d', 'c']; 
usort($original, function ($a, $b) use ($priority) { 

    $prioA = array_search($a['value'], $priority); 
    $prioB = array_search($b['value'], $priority); 

    if ($prioA !== false && $prioB !== false) { 
     if ($prioA < $prioB) return -1; 
     return 1; 
    } 
    if ($prioA !== false) return -1; 
    if ($prioB !== false) return 1; 

    return 0; 
}); 
+0

谢谢!这工作!但是我怎么会在那里得到$?使用['d','c']不是一个选项,因为这个数组是动态的 –

+0

我已经更新了将'$ priority'传递给闭包 – NDM

+0

你是最棒的! –