繁体   English   中英

如何在多维数组中自动设置索引键

[英]How to set index key automatically in multidimensional array

这是我的旧数组。

$oldarray = Array
    (
        [0] => http://test.to/getac/l4p0y6ziqt9h
        [mock] => stdClass Object
            (
                [0] => http://test.to/getae/vidzichawal1
                [1] => http://test.to/getae/vidzi6
                [4] => http://test.to/getae/1x5fbr9t64xn
                [2] => http://test.to/getae/vidzi7
            )

    )

我想与这个新数组合并:

$newarray =  Array
    (
        [mock] => Array
            (
                [0] => http://test.to/getae/vidzichawal2
            )

    )

我正在通过array_merge_recursive($oldarray, $newarray);合并数组array_merge_recursive($oldarray, $newarray);

结果是这样的:

Array
(
    [0] => http://test.to/getac/l4p0y6ziqt9h
    [mock] => Array
        (
            [0] => http://test.to/getae/vidzi5
            [1] => http://test.to/getae/vidzi6
            [4] => http://test.to/getae/1x5fbr9t64xn
            [2] => http://test.to/getae/vidzi7
            [0] => http://test.to/getae/vidzichawal1
        )
);

一切正常,但有一个问题,当我在循环中使用此链接时,您会看到结果是双0键,只有1个链接检索为0,我想像0 1 2 3 4 5 6那样自动设置此键,然后转到合并后继续。

我希望你明白我想要的谢谢

使用array_merge()

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

上面的示例将输出:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

参考

注意您不能有重复的键!

更新

使用array_merge_recursive()示例

<?php
$oldarray = array('http://test.to/getac/l4p0y6ziqt9h', 'mock' => array('http://test.to/getae/vidzichawal1', 'http://test.to/getae/vidzi6', 'http://test.to/getae/1x5fbr9t64xn', 'http://test.to/getae/vidzi7'));
$newarray = array('mock' => array('http://test.to/getae/vidzichawal2'));

$result = array_merge_recursive($oldarray, $newarray);

var_dump($result);
?>

输出值

array (size=2)
  0 => string 'http://test.to/getac/l4p0y6ziqt9h' (length=33)
  'mock' => 
    array (size=5)
      0 => string 'http://test.to/getae/vidzichawal1' (length=33)
      1 => string 'http://test.to/getae/vidzi6' (length=27)
      2 => string 'http://test.to/getae/1x5fbr9t64xn' (length=33)
      3 => string 'http://test.to/getae/vidzi7' (length=27)
      4 => string 'http://test.to/getae/vidzichawal2' (length=32)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM