使用 FOR 或 FOREACH 循环无限循环数组中的数据?

发布于 2025-01-10 12:52:42 字数 798 浏览 0 评论 0原文

如果我可以循环这个水平数据数组,无论添加多少数据数组,有没有办法循环该垂直数据数组,无论添加多少数据?

// Expect Many arrays of data will be added
$array = [
[1,2,3,4,5],
[101,102,103,104,105],
[10,20,30,40,50],
[210,220,230,240, 250 => ['x','y','z'] ],
[100,200,300,400,500, ['a','b','c'] ],
];

// Loop the array data as added
// Loop Horizontal no matter how many arrays of data's will added

for ( $i=0; $i < count($array) ; $i++) {

echo "<pre>";
print_r($array[$i]);
echo "</pre>";

}
// How can I loop this array using FOR loop or FOREACH loop ?
// This will loop Vertical Expect that many arrays of data will added or appended on it .

 [210,220,230,240, 250 => ['x','y','z'] ],
 [100,200,300,400,500, ['a','b','c'] ]

结果:数组转换为字符串

  • 提前致谢

If I can loop this Horizontal array of data no matter how many arrays of data will add, Is there a way to loop that Vertical array of data no matter how many data will be added?

// Expect Many arrays of data will be added
$array = [
[1,2,3,4,5],
[101,102,103,104,105],
[10,20,30,40,50],
[210,220,230,240, 250 => ['x','y','z'] ],
[100,200,300,400,500, ['a','b','c'] ],
];

// Loop the array data as added
// Loop Horizontal no matter how many arrays of data's will added

for ( $i=0; $i < count($array) ; $i++) {

echo "<pre>";
print_r($array[$i]);
echo "</pre>";

}
// How can I loop this array using FOR loop or FOREACH loop ?
// This will loop Vertical Expect that many arrays of data will added or appended on it .

 [210,220,230,240, 250 => ['x','y','z'] ],
 [100,200,300,400,500, ['a','b','c'] ]

Result: Array conversion to string

  • Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鹊巢 2025-01-17 12:52:42

如果您希望递归地循环遍历数组,当您在数组中找到数组时,您也可以循环遍历该数组,这是一种方法:

function recursive_loop( $array ) {
    foreach( $array as $key => $value ) {
        if ( is_array( $value ) ) {
            recursive_loop( $value );
        } else {
            // Do whatever thing you want to do with each value
        }
    }
}

$array = [
    [1,2,3,4,5],
    [101,102,103,104,105],
    [10,20,30,40,50],
    [210,220,230,240, 250 => ['x','y','z'] ],
    [100,200,300,400,500, ['a','b','c'] ],
];

recursive_loop($array);

If you're looking to loop through an array recursively where when you find an array inside an array, you loop through that as well, here's a way to do that:

function recursive_loop( $array ) {
    foreach( $array as $key => $value ) {
        if ( is_array( $value ) ) {
            recursive_loop( $value );
        } else {
            // Do whatever thing you want to do with each value
        }
    }
}

$array = [
    [1,2,3,4,5],
    [101,102,103,104,105],
    [10,20,30,40,50],
    [210,220,230,240, 250 => ['x','y','z'] ],
    [100,200,300,400,500, ['a','b','c'] ],
];

recursive_loop($array);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文