douduoyan5943 2017-09-12 04:54
浏览 44
已采纳

将2个阵列组合成2d阵列​​而不会丢失数据

I have 2 arrays and want to combine into third array with one array as key and another as value. I tried to use array_combine(), but the function will eliminate all the repeated keys, so I want the result array as a 2d array. The sample array is as below:

$keys = {0,1,2,0,1,2,0,1,2};
$values = {a,b,c,d,e,f,g,h,i};
 $result = array(
    [0]=>array(0=>a,1=>b,2=>c),
    [1]=>array(0=>d,1=>e,2=>f),
    [2]=>array(0=>g,1=>h,2=>i)
 );
//What i am using right now is: 
$result = array_combine($keys,$values);

But it only returns array(0=>g,2=>h,3=>i). Any advice would be appreciated!

  • 写回答

2条回答 默认 最新

  • dongnuo4594 2017-09-12 05:05
    关注

    You can do it like below:-

    <?php
    
    $keys = array(0,1,2,0,1,2,0,1,2);
    $values = array('a','b','c','d','e','f','g','h','i');
    
    $values = array_chunk($values,count(array_unique($keys)));
    
    foreach($values as &$value){
       $value = array_combine(array_unique($keys),$value);
    }
    
    print_r($values);
    

    https://eval.in/859753

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?