简体   繁体   English

数组被php中的最后一个元素覆盖

[英]array is overwritten by the last element in php

The result stored in $g is 1 and 2. The following code I've written below, my $array['music'] stores only the last element that is 2. But what I want is to execute my sql query 2 times under foreach and match the value of $g which is 1 and 2 with mu_id ( mu_id is the column name from another table music ) and store all the rows data of row 1 and 2 in to $array['music'] . 存储在$g的结果是1和2。下面我写的以下代码$array['music']仅存储最后一个元素2。但是我想要的是在下面执行2次sql查询foreach并将$g的值1和2与mu_idmu_id是来自另一种music的列名),并将行1和2的所有行数据存储到$array['music']

It is storing only for the second row (2) not for 1 or it is overwriting it when it is executing for the second time inside loop. 它仅为第二行(2)存储而不为1存储,或者在第二次在循环内执行时覆盖它。 If there is any logic to make it work then please let me know. 如果有任何逻辑可以使其正常工作,请告诉我。

    foreach($genre as $g)
    {
        echo $g;
        echo "<br>";
        $array['music'] = $m -> where('mu_id', $g ) -> get();
    }

You're redeclaring the entire array each time rather than adding to it, use this instead: 您每次都在重新声明整个数组,而不是在整个数组中进行声明,而应使用以下代码:

foreach($genre as $g)
{
    $array['music'][] = $m->where('mu_id', $g)->get();
}

Or even better, less queries: 甚至更好,查询更少:

$array['music'] = $m->where_in('mu_id', $genre)->get();

如果要将所有数据存储在数组中,则应使用$array['music'][]而不是$array['music']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM