使用PHP合并foreach循环内的数组

时间:2014-10-14 13:44:22

标签: php arrays

我有以下数组:

Array
(
    [0] => ALFA01
    [1] => BETA02
    [2] => GAMMA03
    [3] => DELTA04
    [4] => EPSILON05
    [5] => ZETA06
    [6] => THETA07
    [7] => IOTA08
    [8] => KAPPA09
    [9] => LAMBDA10
)

然后我按以下方式将值分成字符和数字:

foreach($portfolio as $value) {
    $char = substr("$value", 0, 2);
    $numb = substr("$value", 2);

并使用此值进行查询:

    $query = "
        SELECT id, typ1, typ2, typ3
        FROM data_table
        WHERE char = '$char'
        AND numb = $numb
        LIMIT 1";

    $result = mysqli_query($mysqli, $query);

    //Now we have some important variables that will help finding our result.
    while($row = mysqli_fetch_array($result)) {
        $id = $row['id'];
        $typ1 = $row['typ1'];
        $typ2 = $row['typ2'];
        $typ3 = $row['typ3'];
    }

然后我做一些查询,如果typ * = 1(它可能只有0或1)。

if ($typ1 == 1) {
    $query_id_num2 = "
        SELECT id_num2
        FROM values_table01
        WHERE id_num1 = $id";
    $result_id_num2 = mysqli_query($mysqli, $query_id_num2);

    // Return an array with all ids.
    $id_num2_typ01 = array();
    while($row = mysqli_fetch_array($result_appln_id_num2)) {
        $id_num2_typ01[] = ($row['id_num2']);
    }
}

/ ==编辑== /

在每种不同的类型中,我们都有不同的values_table。 我现在正在编写typ2的完整查询,因此将予以强调。

// == / EDIT == /

然后我对typ2和typ3做同样的事情......

if ($typ2 == 1) {
    $query_id_num2 = "
        SELECT id_num2
        FROM values_table02
        WHERE id_num1 = $id";
    $result_id_num2 = mysqli_query($mysqli, $query_id_num2);

    // Return an array with all ids.
    $id_num2_typ02 = array();
    while($row = mysqli_fetch_array($result_appln_id_num2)) {
        $id_num2_typ02[] = ($row['id_num2']);
    }
}

最后我合并了三个数组(如果已设置)并在屏幕上打印结果:

// typ01
if (isset($id_num2_typ01)){
    $id_num2_typ01 = $id_num2_typ01;
} else {
    $id_num2_typ01 = array();
}

// typ02
if (isset($id_num2_typ02)){
    $id_num2_typ02 = $id_num2_typ02;
} else {
    $id_num2_typ02 = array();
}

// typ03
if (isset($id_num2_typ03)){
    $id_num2_typ03 = $id_num2_typ03;
} else {
    $id_num2_typ03 = array();
}

// merge arrays
$id_num2 = array_merge($id_num2_typ01,$id_num2_typ02,$id_num2_typ03);

// print it on screen
echo '<pre>id_num2:<br />';
print_r($appln_idNum2);
echo '</pre>';

} // this closes the above foreach, i.e. the code will loop to every value of the first array 

结果我收到了以下数据:

id_num2:
Array
(
    [0] => 41558194
    [1] => 44677841
    [2] => 44503689
    [3] => 40651770
    [4] => 41667291
)

id_num2:
Array
(
    [0] => 15458354
    [1] => 35477154
    [2] => 15703123
    [3] => 95151111
    [4] => 55567125
)

etc.

在我们的例子中,我们将有10个这样的小阵列。

我的问题是:如何合并这个小数组,以便我只有一个数组?

感谢您帮助解决此特定问题。也许还有另一种可能性来编写代码以使其更好,更有效。

0 个答案:

没有答案