将动态数组添加到静态数组PHP的末尾

时间:2019-07-16 18:47:52

标签: php arrays multidimensional-array

我在sql循环中找到了以下代码,以确定我在电子表格上输出了多少行。基本上不需要粘贴全部内容,因为这是一个很长的语句,顶部的SQL语句将返回60行,其中将包含我输入到原始$data1数组中的变量。

$stmt2= $mysqV1->prepare("SELECT DISTINCT master_recipe, recipe, matl_id, comp_length, comp_width, comp_tck from components where recipe > 0 and matl_id > 0 order BY  CAST(recipe AS UNSIGNED) ASC" );

foreach ($result2 as $key2=>$value2)
  {
 $data1[]=(array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck));
  }

然后,我还有另一个嵌套循环(在原始$result2循环内),该循环将确定我添加到该数组的元素个数,因为值将在记录之间变化。我试图声明一个数组,然后使用数组推入和数组合并,但是它们似乎都没有达到我想要的效果。

$temp7 = array($master_recipe);
$stmt7= $mysqV1->prepare("Select * from machine where master_recipe = ? order by route_header_id asc" );
$stmt7->execute($temp7);
$result7=$stmt7->fetchAll();
foreach ($result7 as $key7=>$value7)
{
    $station_id = $value7['route_header_id'];
    $time_taken = $value7['time_hrs'];
    $a[] = (array("StationID"=>$time_taken));
    array_push($data1,$a);
}

所以我要做的是将$a的内容添加到$data1的末尾,给我1个数组值,然后将其打印到电子表格中(打印部分已经在工作了$data1数组),但未在其中添加$ a。

最终结果,我想为$data1

中的值添加类似的内容
$data1[]=(array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck,"$station_id1"=>$time_taken,"$station_id2"=>$time_taken2,"$station_id3"=>$time_taken3));

2 个答案:

答案 0 :(得分:3)

$data1变量中添加要添加到$a的行,然后在将其推入$data1之前可以向该行添加新元素。

foreach ($result2 as $value2) {
    $master_recipe = $value2['master_recipe'];
    $recipe = $value2['recipe'];
    ...
    $a = array("Master Recipe"=>$master_recipe,"Recipe"=>$recipe,"Recipe Name"=>$recipe_name,"Material"=>$material,"Length"=>$comp_length,"Width"=>$comp_width,"Thickness"=>$comp_tck);
    $temp7 = array($master_recipe);
    $stmt7= $mysqV1->prepare("Select route_header_id, time_hrs from machine where master_recipe = ? order by route_header_id asc" );
    $stmt7->execute($temp7);
    while ($value7 = $stmt7->fetch())
    {
        $station_id = $value7['route_header_id'];
        $time_taken = $value7['time_hrs'];
        $a[$station_id] = $time_taken;
    }
    $data1[] = $a;
}

答案 1 :(得分:2)

如果您将$data1的初始集合更改为此:

$data1= array(
    "Master Recipe"=>$master_recipe,
    "Recipe"=>$recipe,
    "Recipe Nme"=>$recipe_name,
    "Material"=>$material,
    "Length"=>$comp_length,
    "Width"=>$comp_width,
    "Thickness"=>$comp_tck
);

然后,在您的循环中。

foreach ($result7 as $key7=>$value7)
{
    $station_id = $value7['route_header_id'];
    $time_taken = $value7['time_hrs'];
    $data1[$station_id] = $time_taken;
}
相关问题