PHP-如何获取n个深层数组的所有数组值? [英] PHP - How to get all Array Values of an n deep miltidimentional array?

查看:52
本文介绍了PHP-如何获取n个深层数组的所有数组值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个多维数组的所有数组值,但问题是数组的深度可以为1或2、3或4,即n个深度。

i am trying to get all array values of an multidimentional array, but the thing is array can be 1 levels deep or 2, 3 or 4 , i.e. n levels deep.

这是一些随机的,例如数组内容。

here are some random e.g. of array contents.

eg1

Array
(
    [0] => Array
        (
            [0] => name0
        )
    [1] => Array
        (
            [0] => name1
        )
    [2] => Array
        (
            [0] => name2
        )
    [3] => Array
        (
            [0] => name3
        )
    [4] => Array
        (
            [0] => name4
        )
    [5] => Array
        (
            [0] => name4
        )
    [6] => Array
        (
            [0] => name5
        )
)

eg2

Array
(
    [0] => Array
        (
            [0] => name0
            [1] => name1
            [2] => name2
            [3] => name3
            [4] => name4
            [5] => name5
        )
)

我希望所有值都在新数组中。
到目前为止,我已经尝试过类似的事情。

I want all values to be in new array. So far i have tried something like this.

使用 foreach 循环n次现在可以正常工作,但是我想知道它在程序上是否正确,或者是否有比此方法更快或更更好的方法。

looping for n times using foreach loop, its working fine for now, but i would like to know if its programmatically correct or is there any other way which is faster or better than this one.

PHP代码。

<?php
$out_final_array = array ();
function foreach_values_endless($array){
global $out_final_array;
    /* if its array */
    if(is_array($array)){
        /*run foreach loop to find more sub arrays */
        foreach ($array as $value){
            /* if value is an array send to own custom function */
            if(is_array($value)){
                $out_final_array[] = foreach_values_endless(array_values($value));
            }else{
            /* value is not an array*/
                $out_final_array[] = $value;
            }
        }
    }else{
        /* value is not array */
        $out_final_array[] = $array;
    }
}


推荐答案

如果您需要将其展平,另一种方法是使用SPL RecursiveArrayIterator RecursiveIteratorIterator

If you need to flatten it, another way would be to use SPL RecursiveArrayIterator and RecursiveIteratorIterator:

$new_data = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
foreach($it as $v) {
    $new_data[] = $v;
}

示例输出

旁注:不需要 global 只需让它返回值即可

Sidenote: No need for that global just have it return the values:

function foreach_values_endless($array){
    $data = array();

    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $data = array_merge($data, foreach_values_endless($v));
        } else {
            $data[] = $v;
        }
    }

    return $data;
}

示例输出

这篇关于PHP-如何获取n个深层数组的所有数组值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆