Combining Three Arrays in foreach loop in PHP

社会主义新天地 提交于 2021-02-05 09:45:53

问题


I know how to combine two arrays in foreach loop using array_combine() function of PHP

But I have three arrays and I want to loop through all of three arrays at a time.

$get_id=$data->get_id;
$get_product=$data->get_product;
$get_comment=$data->get_comment;

foreach (array_combine($get_id, $get_product) as $id => $product) {
    echo "$id - $product<br/>";

}

I want to iterate $get_comment array too in this loop.

Thanks


回答1:


I think this might be what you are looking for:

$get_id=$data->get_id;
$get_product=$data->get_product;
$get_comment=$data->get_comment;

foreach($get_id as $i => $id){
    $product = $get_product[$i];
    $comment = $get_comment[$i];
    echo "$id , $product, $comment<br/>";
}

This solution assumes the $get_id, $get_product, and $get_comment arrays are all indexed the same way.




回答2:


Combine the arrays before the foreach loop

    $comment_array = array_combine($get_id, $get_comment);
    $product_array = array_combine($get_id, $get_product);
    foreach ($product_array as $id => $product) {
      $comment = $comment_array[$id];
    }


来源:https://stackoverflow.com/questions/23227658/combining-three-arrays-in-foreach-loop-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!