2017-09-12 69 views
2

我有2個數組,如下所示。將2個數組組合成第三個數組,其中包含一個數組中不固定的唯一鍵

$keys = [1,2,3,4-1,99,1,2,3,4-1,4-2,4-3,99,1,2,3,4-1,4-2,99] 
$values = [a,b,c,d,x,a1,b1,c1,d1,e,g,x,a2,b2,c2,d2,e,x] 

我想結合到一個數組,如:

$result = array(
    [0]=>array(1=>a,2=>b,3=>c,4-1=>d,99=>x), 
    [1]=>array(1=>a1,2=>b1,3=>c1,4-1=>d1,4-2=>e,4-3=>g,99=>x), 
    [2]=>array(1=>a2,2=>b2,3=>c2,4-1=>d2,4-2=>e,99=>x 
); 

規則是隨時突破$關鍵= 99。 目前,我嘗試使用array_chunk,但語法只允許我通過唯一鍵的數量對數組進行塊化,這在我的示例中不是常量。 有什麼建議嗎?

+0

添加你嘗試過什麼。 '$ keys'和'$ values'不是數組! – Thamilan

回答

1

您需要編寫一個自定義腳本,通過您的邏輯組合這兩個數組。

您需要從$keys陣列中提取每個密鑰,並將其與$values陣列中的位置相同。

例子:

<?php 
$keys = ['1', '2', '3', '4-1', '99', '1', '2', '3', '4-1', '4-2', '4-3', '99', '1', '2', '3', '4-1', '4-2', '99']; 
$values = ['a', 'b', 'c', 'd', 'x', 'a1', 'b1', 'c1', 'd1', 'e', 'g', 'x', 'a2', 'b2', 'c2', 'd2', 'e', 'x']; 

$i = 0; 
$result = []; 
foreach ($keys as $index => $key) { 
    if (empty($result[$i])) 
     $result[$i] = [$key => $values[$index]]; 
    else 
     $result[$i][$key] = $values[$index]; 

    if ($key == 99) 
     ++$i; 
} 

print_r($result); 
+0

問題解決!萬分感謝! – Tedxxxx

0

您可以使用foreach循環來實現這一

$keys = ["1","2","3","4-1","99","1","2","3","4-1","4-2","4-3","99","1","2","3","4-1","4-2","99"]; 
$values = ["a","b","c","d","x","a1","b1","c1","d1","e","g","x","a2","b2","c2","d2","e","x"]; 
$new_array = array(); 
$split_at = "99"; 
$i = 0; 
foreach ($keys as $key => $value) { 
    $new_array[$i][$value] =$values[$key]; 

    if($split_at == $value){ 
    $i++; 
    } 
} 

print_r($new_array); 

DEMO

相關問題