如何在PHP中更改关联数组值

时间:2019-03-19 10:34:02

标签: php arrays

$arr = array(
  0 => array(
        0 => 'one',
        1 => 'two',
        2 => 'three'
        ),
  1 => array(
        0 => 'sun',
        1 => 'mon',
        2 => 'tues'
        ),
  2 => array(
        0 => 'jan',
        1 => 'feb',
        2 => 'march'
        )
  );

这是数组,我想要这样的结果。数组有一个子数组,并且想要更改子数组的值。

$arr = array(
  0 => array(
        0 => 'one',
        1 => 'sun',
        2 => 'jan'
        ),
  1 => array(
        0 => 'two',
        1 => 'mon',
        2 => 'feb'
        ),
  2 => array(
        0 => 'three',
        1 => 'tues',
        2 => 'march'
        )
  );

请提供解决方案。预先感谢!

4 个答案:

答案 0 :(得分:7)

尝试使用此循环处理您的要求

输出

  

Array([0] => Array([0] =>一个[1] => sun [2] => jan)[1] => Array([0] =>两个[1] => mon [2] =>二月)[2] =>数组([0] =>三个[1] =>周二[2] =>三月))

代码

<?php 
$arr = array(
        0 => array(
                    0 => 'one',
                    1 => 'two',
                    2 => 'three'
                    ),
        1 => array(
                    0 => 'sun',
                    1 => 'mon',
                    2 => 'tues'
                    ),
        2 => array(
                    0 => 'jan',
                    1 => 'feb',
                    2 => 'march'
                    )
        );
    $newarray = [];
    $length = count($arr[0]); 
    foreach ($arr as $key => $value) {
        for ($i=0; $i < $length; $i++) { 
            $newarray[$i][$key] = $value[$i];

        }
        //break;
    }
    print_r($newarray);

答案 1 :(得分:0)

要更改子数组项的值,只需添加另一个[]部分:

$arr[0][1] = 'sun';

答案 2 :(得分:0)

我以递归的方式实现了。

$arr = array(
        0 => array(
                    0 => 'one',
                    1 => 'two',
                    2 => 'three'
                    ),
        1 => array(
                    0 => 'sun',
                    1 => 'mon',
                    2 => 'tues'
                    ),
        2 => array(
                    0 => 'jan',
                    1 => 'feb',
                    2 => 'march'
                    )
        );

$new_arr = array();
$nb = count($arr);
$i = 0;
while($nb > 0){
    $nb--;
    $val1 = $arr[0][$i];
    $val2 = $arr[1][$i];
    $val3 = $arr[2][$i];
    $new_array[] = array($val1, $val2, $val3);
    $i++;
}

print_r($new_array);

您可以在此处http://sandbox.onlinephpfunctions.com/code/e9e87de78f7b9dbb6edc72340d60f8b31a77875f

进行检查

答案 3 :(得分:0)

您可以使用具有null的array_map函数作为回调。

$arr = array_map(
  null,
  $arr[0],
  $arr[1],
  $arr[2]
);

print_r($arr);

//Output

Array
(
[0] => Array
    (
        [0] => one
        [1] => sun
        [2] => jan
    )

[1] => Array
    (
        [0] => two
        [1] => mon
        [2] => feb
    )

[2] => Array
    (
        [0] => three
        [1] => tues
        [2] => march
    )
)