0

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
  • 4
    $arr[45] = $arr[0]; unset($arr[0]);? Commented Nov 25, 2012 at 22:25

3 Answers 3

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);
0
1

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"
  }
}
0
$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 .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.