将三个数组合并为一个foreach

时间:2018-07-13 07:37:55

标签: php arrays

$cats_array = array(1,7,28);

foreach ($cats_array as $category) {
    $category_field_query = "SELECT fields 
                             FROM categories 
                             WHERE status = 1 AND id = $category";
    $category_field_query_run = mysqli_query($connect, $category_field_query);
    $cat_field = mysqli_fetch_object($category_field_query_run);

    $field = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
    $field = str_replace("/","",$field); /* Delete all '/' */

    print_r($field);
}

在foreach循环中,我的查询每转一圈都会从字段中返回类似/7/,/13/,/24/的内容,然后将其从斜杠和逗号中清除。

我的目标是将所有阵列收集在一个阵列中

我试图在foreach之外创建一个空数组,并对所有数组求和,但返回空。

3 个答案:

答案 0 :(得分:0)

我不明白为什么要存储这样的字段,但这是一个可能的解决方案:

$fields = array();
$cats_array = array(1,7,28);

foreach ($cats_array as $category) {
    $category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
    $category_field_query_run = mysqli_query($connect, $category_field_query);
    $cat_field = mysqli_fetch_object($category_field_query_run);

    preg_match_all('/\/(\d+)\//', $cat_field->fields, $matches);

    if (!empty($matches[1])) {
         $fields = array_merge($fields, $matches[1]);
    }
}

print_r($fields);

答案 1 :(得分:0)

$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
    $category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id= $category";
    $category_field_query_run = mysqli_query($connect, $category_field_query);
    $cat_field = mysqli_fetch_object($category_field_query_run);
    $field = explode(",", $cat_field->fields); // Explode ',' from '/'3'/,'
    $field = str_replace("/", "", $field);
    $fields[] = $field;
}
print_r($fields);

答案 2 :(得分:0)

必须在$filed循环之前将foreach定义为数组。现在您可以将值存储到$filed中。请注意,您必须使用多维数组来存储值。

$cats_array = array(1,7,28);
$field = array();
foreach ($cats_array as $category) {
    $category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
    $category_field_query_run = mysqli_query($connect, $category_field_query);
    $cat_field = mysqli_fetch_object($category_field_query_run);

    $field1 = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
    $field[] = str_replace("/","",$field1); /* Delete all '/' */
} 
print_r($field);