PHP Replace multidimensional array keys

て烟熏妆下的殇ゞ 提交于 2019-12-25 11:26:07

问题


I would like to replace some keys, my array is:

Array
(
    [0] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
            [3] => test4
            [4] => test5
            [5] => test6
        )

    [1] => Array
        (
            [0] => test7
            [1] => test8
            [2] => test9
            [3] => test10
            [4] => test11
            [5] => test12
        )

)

My wish:

Array
(
    [45] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
            [3] => test4
            [4] => test5
            [5] => test6
        )

    [51] => Array
        (
            [0] => test7
            [1] => test8
            [2] => test9
            [3] => test10
            [4] => test11
            [5] => test12
        )

)

45 and 51 are examples.

How can I do that? I tried array_flip() then array_search() but PHP says: "Can only flip STRING and INTEGER values!"

Thank's anyway. Regards


回答1:


$old_array = array(
    0 => array(0=>'test1',1=>'test2',2=>'test3',3=>'test4',4=>'test5',5=>'test6'),
    1 => array(0=>'test1',1=>'test2',2=>'test3',3=>'test4',4=>'test5',5=>'test6')
);
$new_array = array(
    45=>$old_array[0],
    51=>$old_array[1]
);
var_dump($new_array);



回答2:


A key in an array can be modified by setting the the new key to the value of the old key and then unsetting the old key.

$myArray = array(
    "0" => array("0" => "test1", "1" => "test2"),
    "1" => array("0" => "test3", "1" => "test4"));

echo "original array:\n";
var_dump($myArray);

// modify keys
$myArray["45"] = $myArray["0"];
unset($myArray["0"]);
$myArray["51"] = $myArray["1"];
unset($myArray["1"]);

echo "modified array:\n";
var_dump($myArray);

generates:

original array:
array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "test1"
    [1]=>
    string(5) "test2"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "test3"
    [1]=>
    string(5) "test4"
  }
}

modified array:
array(2) {
  [45]=>
  array(2) {
    [0]=>
    string(5) "test1"
    [1]=>
    string(5) "test2"
  }
  [51]=>
  array(2) {
    [0]=>
    string(5) "test3"
    [1]=>
    string(5) "test4"
  }
}



回答3:


$keys = array('45','51');
$count = 6 ;
$i = 0;
foreach($keys as $key){
   for($l = 0;$l<$count;$l++){
      $last[$key][$l] = 'test'.$l+$i+1 ;
   }
  $i += $count;
}
print_r($last);

set $count to any number of arrays that you want .



来源:https://stackoverflow.com/questions/13556151/php-replace-multidimensional-array-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!