如何将foreach的值存储为数组

时间:2016-03-08 10:18:58

标签: php

<?php 
  $samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

  foreach ($samgri as $row){
    $puja_samagri = $row['puja_samagri'];
  }
  $puja_sam = explode(',', $puja_samagri);

  foreach ($puja_sam as $samagri_id){
    $samg  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
  }

  if(sizeof($samg) == 0){
    echo '<h5 style = "text-align:center">No samagari available</h5>';
  }else{
    foreach ($samg as $row){


?>

但它只获取最后一条记录而不是总记录

2 个答案:

答案 0 :(得分:1)

您应该在数组名称之后添加括号,如:

&#13;
&#13;
<?php 
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

//Declare the arrays
$puja_samagri = new array();
$samg = new array();

foreach ($samgri as $row){

$puja_samagri[] = $row['puja_samagri'];

}

$puja_sam     = explode(',', $puja_samagri);

foreach ($puja_sam as $samagri_id){

$samg[]  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}

if(sizeof($samg) == 0){

echo '<h5 style = "text-align:center">No samagari available</h5>';

}else{

foreach ($samg as $row){


?>
&#13;
&#13;
&#13;

它将使用自动int位置(从0开始直到你得到所有结果)。在使用它们之前将它们声明为数组也是一个好主意。

答案 1 :(得分:0)

你需要在每个foreach之后获取数组,如下所示:

<?php 
$samgri = $this->crud_model->get_puja_samagri_by_puja_order($param1,$param);

foreach ($samgri as $row){

$puja_samagri[] = $row['puja_samagri'];

}

$puja_sam     = explode(',', $puja_samagri);

foreach ($puja_sam as $samagri_id){

$samg[]  = $this->crud_model->get_puja_samagri_by_id($samagri_id);
}

if(sizeof($samg) == 0){

echo '<h5 style = "text-align:center">No samagari available</h5>';

}else{

foreach ($samg as $row){


?>

希望这会对你有所帮助:)。