【问题标题】:Get values of array outside while loop在while循环外获取数组的值
【发布时间】:2017-01-31 10:12:36
【问题描述】:

为什么我只能在 while 循环之外获取此数组中的最后一个值。它不应该保存所有记录吗?为什么没有使用查询中的所有值构建数组?

这是我的代码。

$cost_array = array(); 
if ($stmt = $conn_mysqli -> prepare("SELECT costs_items.cno, costs_items.name,costs_items.description, costs_items.type,costs_items.measure, costs_items.amount, costs_items.vc_fc,costs_items_custom.cno, costs_items_custom.name, costs_items_custom.description, costs_items_custom.type, costs_items_custom.measure, costs_items_custom.amount, costs_items_custom.vc_fc FROM costs_items LEFT JOIN costs_items_custom ON costs_items.costs_id = costs_items_custom.costs_id WHERE costs_items.costs_id = ?")) {
         $stmt -> bind_param("i", $costs_select);   
         $stmt -> execute();
         $stmt -> bind_result($cno, $cost_name, $cost_description, $cost_type, $cost_measure, $cost_amount, $cost_vcfc, $ccustom_cno, $ccustom_name, $ccustom_description, $ccustom_type, $ccustom_measure, $ccustom_amount, $ccustom_vc_fc);
         while($stmt -> fetch()){

            //Here we put all costs in array
            $cost_array['cno'] = $cno;
            $cost_array['cost_name'] = $cost_name;
            $cost_array['cost_description'] = $cost_description;
            $cost_array['cost_type'] = $cost_type;
            $cost_array['cost_measure'] = $cost_measure;
            $cost_array['cost_amount'] = $cost_amount;
            $cost_array['cost_vcfc'] = $cost_vcfc;

        }
        $stmt -> close();                                      }

    var_dump($cost_array);

【问题讨论】:

    标签: php arrays loops


    【解决方案1】:

    将您的代码更改为:使用[] 创建新索引。

     $cost_array = array(); 
    while($stmt -> fetch()){
        $cost_array['cno'][] = $cno;
        $cost_array['cost_name'][] = $cost_name;
        $cost_array['cost_description'][] = $cost_description;
        $cost_array['cost_type'][] = $cost_type;
        $cost_array['cost_measure'][] = $cost_measure;
        $cost_array['cost_amount'][] = $cost_amount;
        $cost_array['cost_vcfc'][] = $cost_vcfc;
    
    }
    $stmt -> close();          
    
    var_dump($cost_array);//all your values
    

    【讨论】:

    • 就是这样。谢谢!
    【解决方案2】:

    试试这个方法

     $cost_array[] = array(
          'cno' => $cno,
          'cost_name' => $cost_name,
          'cost_description' => $cost_description
        );
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 2014-06-20
      • 2020-08-16
      • 2017-12-11
      • 2016-04-29
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多