开发者

How to rekey numerical array keys

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_m开发者_JAVA技巧atrix[$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
        )
)


Try use: instead of this:

  $temp_matrix[$k++] = $v;

do this:

 $temp_matrix[++$k] = $v;


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


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


Could do something like ...

    foreach ($matrix as $k=>$v) {
        foreach ($v as $k2=>$v2) {
            $tmp_arr[$k][$k2+1] = $v2;
        }
    }
    $matrix = $tmp_arr;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜