Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

change inner key in multidimensional array php

I want to ask about how to replace inner key in a multidimensional array. I have an multidimensional array :

$array1=
array(array(5000, 6,  325,  3,  3,  517000000),
      array( 20000,  5,  217,  5,  3,  1692000000)
      );

The second array is

$array2=array(1,2,3,4,5,6);

I expected the new array is

Array(
[0] => Array
    (
        [1] => 5000
        [2] => 6
        [3] => 325
        [4] => 3
        [5] => 3
        [6] => 517000000
    )

[1] => Array
    (
        [1] => 20000
        [2] => 5
        [3] => 217
        [4] => 5
        [5] => 3
        [6] => 1692000000
    ))

I have tried this code below by another post PHP Replace multidimensional array keys, but I can't assign the value of my array1

foreach($array2 as $array2 ){
    for($k=0;$k<sizeof($array2);$k++){
        for($l=0;$l<$count;$l++){
        $last[$l][$array2] = $array1[$k][$l];
    }
    $i += $count;
    }

}

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @Rizier has suggested in his comment you can do this using array_map() and array_combine().

<?php
$array1=
array(array(5000, 6,  325,  3,  3,  517000000),
      array( 20000,  5,  217,  5,  3,  1692000000)
      );
$array2 = array(1, 2, 3, 4, 5, 6);

foreach($array1 as $arr1){
    $array3[] = array_combine($array2, $arr1);
}
var_dump($array3);

output

  array (size=2)
      0 => 
        array (size=6)
          1 => int 5000
          2 => int 6
          3 => int 325
          4 => int 3
          5 => int 3
          6 => int 517000000
      1 => 
        array (size=6)
          1 => int 20000
          2 => int 5
          3 => int 217
          4 => int 5
          5 => int 3
          6 => int 1692000000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...