Home > Backend Development > PHP Tutorial > php操作数组

php操作数组

WBOY
Release: 2016-06-23 14:15:20
Original
836 people have browsed it

for($i=1;$i<=5;$i++){	array(array($i));}
Copy after login


for循环里面的是一个二维数组,我想把for循环里面的二维数组进行合并,打印出来的结果是:

array( [0] => Array        (      [0] => 1     ) [1] => Array        (      [0] => 2       ) [2] => Array        (      [0] => 3      ) [3] => Array        (      [0] => 4  ) [4] => Array        (       [0] => 5       ))
Copy after login


回复讨论(解决方案)

$rs = array();for($i=0; $i<=5; $i++) {    $rs[] = array($i);}
Copy after login
Copy after login
Copy after login

$rs = array();for($i=0; $i<=5; $i++) {    $rs[] = array($i);}
Copy after login
Copy after login
Copy after login

这个方法不行,右边的array(array($i));你是不能拆的,必须是一个二维数组。


$rs = array();for($i=0; $i<=5; $i++) {    $rs[] = array($i);}
Copy after login
Copy after login
Copy after login

这个方法不行,右边的array(array($i));你是不能拆的,必须是一个二维数组。
你有没把我的代码运行,看结果没?

我知道这个结果是正确的,但是你不能这样操作

$rs[] = array($i);
Copy after login

右边必须得是:
array(array($i))
Copy after login

$rs = array();for($i=0; $i<=5; $i++) {    $tmp = array(array($i));//这样行吗?    $rs[] = $tmp[0];}
Copy after login
Copy after login

$rs = array();for($i=0; $i<=5; $i++) {    $tmp = array(array($i));//这样行吗?    $rs[] = $tmp[0];}
Copy after login
Copy after login

此方法,不行,你只能得到$i的数字,如果二维数组里面还有其它的元素就无法获取了。

for($i=1;$i<=5;$i++){  $res[$i] = array(array($i));}
Copy after login
Copy after login

for($i=1;$i<=5;$i++){  $res[$i] = array(array($i));}
Copy after login
Copy after login

得到的已经是三维的数组,要的结果是二维数组。

$res = array();for($i=1;$i<=5;$i++){  $res = array_merge($res, array(array($i)));}print_r($res);
Copy after login

Array
(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [0] => 2
        )

    [2] => Array
        (
            [0] => 3
        )

    [3] => Array
        (
            [0] => 4
        )

    [4] => Array
        (
            [0] => 5
        )

)

OK,正解,谢谢老大。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template