如何在 php 中打印随深度变化的多维数组?

How do I print a multidimensional array that varies with depth in php?

我有以下数组输出示例。我需要找到一种方法将此数组转换为字符串或以有组织的方式输出电子邮件。我试过 implode 但我只收到 "Array" 输出。请帮忙!

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

            [1] => Array
                (
                    [0] => test1@gmail.com
                )

            [2] => Array
                (
                    [0] => test2@gmail.com
                )

            [3] => Array
                (
                    [0] => test3@gmail.com
                )

            [4] => Array
                (
                    [0] => test4@gmail.com
                )

            [5] => Array
                (
                    [0] => test5@gmail.com
                )

        )

)
for ($i = 0; $i < count($arr[0]); $i++) {
    for ($j = 0; $j < count($arr[0][$i]); $j++) {
        echo $arr[0][$i][$j];
    }
}

以上将输出数组的每个字符串。
我唯一的问题是为什么要在数组中如此深地存储单个字符串?也许我们可以看到更多代码?

对于您提供的内容,下面的代码会更简单:

$arr[] = "Email";
$arr[] = "test1@gmail.com";
$arr[] = "test2@gmail.com";
$arr[] = "test3@gmail.com";
$arr[] = "test4@gmail.com";
$arr[] = "test5@gmail.com";

for ($i = 0; $i < count($arr); $i++) {
    echo $arr[$i];
}

更好的是,改用数组键:

$arr["Email"][] = "test1@gmail.com";
$arr["Email"][] = "test2@gmail.com";
$arr["Email"][] = "test3@gmail.com";
$arr["Email"][] = "test4@gmail.com";
$arr["Email"][] = "test5@gmail.com";

for ($i = 0; $i < count($arr["Email"]); $i++) {
    echo $arr["Email"][$i];
}

您可以将数组减少一个级别,然后创建一个 foreach 循环,这样您就可以组织它们并根据需要打印每个独特的项目。

array_reduce 将使您不必创建第二个循环,并使您的事情变得更容易,同时占用更少的计算能力。我从 .

那里得到了这个
<?php
// reduce array
array_reduce($array, 'array_merge', []);
// create the loop
foreach ($array as $k => $v)
{
    // this will print the emails in a list format
    echo '<li>' . $v . '</li>';
}
?>

如果某些数组比其他数组更深,另一种解决方案是使用递归打印函数。这样它将遍历每个值,如果该值是一个数组,它将使用该新数组重复该过程,它会找到要打印的不是数组的内容。

$data = array(array(array("Email"),array("some@email.com"),array("another@email.com")),array("outisde@gmail.com"));

function recursivePrint($array) {
    foreach($array as $value) {
        if (gettype($value) === 'array') {
            recursivePrint($value);
        } else {
            print($value . ", ");
        }
    }
}

recursivePrint($data);

这是您唯一需要使用的数组吗?以后还会有这样的阵法吗?内爆仅适用于同一个数组中的兄弟项目,所以你需要这样的东西:

<?php

$array = array(
  "test1@gmail.com",
  "test2@gmail.com",
  "test3@gmail.com",
  "test4@gmail.com",
  "test5@gmail.com"
);

$result = implode( ',', $array );

echo $result;
// test1@gmail.com,test2@gmail.com,test3@gmail.com,test4@gmail.com,test5@gmail.com