Reputation: 1244
I have an array $matrix_part
, containing arrays, and I want to rekey the inner keys to start at 1.
I am trying to code below but it doesn't work - it just stores the new array identically.
$temp_matrix = array();
foreach ($matrix_part as $k => $v){
$temp_matrix[$k++] = $v;
}
$matrix_part = $temp_matrix;
Source array:
Array
(
[0] => Array
(
[0] => 163
[1] => 23
[2] => 97
)
[1] => Array
(
[0] => 163
[1] => 23
[2] => 97
)
[2] => Array
(
[0] => 163
[1] => 23
[2] => 97
)
)
Desired output:
Array
(
[0] => Array
(
[1] => 163
[2] => 23
[3] => 97
)
[1] => Array
(
[1] => 163
[2] => 23
[3] => 97
)
[2] => Array
(
[1] => 163
[1] => 23
[3] => 97
)
)
Upvotes: 1
Views: 1456
Reputation: 144
foreach ($a as $outer_k => $outer_v) {
for ($i = count($outer_v) - 1; $i >= 0; $i--) {
$outer_v[$i+1] = $outer_v[$i];
}
unset($outer_v[0]);
$a[$outer_k] = $outer_v;
}
where $a is your input array
Upvotes: 1
Reputation: 54659
This maybe?
$input = array(
array(163, 23, 97),
array(163, 23, 97),
array(163, 23, 97),
);
$output = array_map(function ($innerArray) {
return array_combine(range(1, sizeof($innerArray)), $innerArray);
}, $input);
print_r($output);
Upvotes: 2
Reputation: 5263
Could do something like ...
foreach ($matrix as $k=>$v) {
foreach ($v as $k2=>$v2) {
$tmp_arr[$k][$k2+1] = $v2;
}
}
$matrix = $tmp_arr;
Upvotes: 1
Reputation: 17447
Try use: instead of this:
$temp_matrix[$k++] = $v;
do this:
$temp_matrix[++$k] = $v;
Upvotes: 2