简体   繁体   English

php组合数组本身

[英]php combining array by itself

why is php combining array when I do foreach.为什么在执行 foreach 时 php 会合并数组。 see below见下文

If I enter the following code, I will get id1 id2 individually.如果我输入以下代码,我将单独获得id1 id2

foreach($array as $value){
    $id = $value->id;
    echo $id;
}

now if I try to use the ids to do a query现在,如果我尝试使用 ID 进行查询

foreach($array as $value){
    $id = $value->id;
    $result = $this->model->run_some_query($id);
    var_dump($result);
}

for the above code.对于上面的代码。 Since I am foreach looping not passing in an array of ids, I expect to get 2 sets of seperate array.因为我 foreach 循环没有传入一个 id 数组,所以我希望得到 2 组单独的数组。 array1 with result from id1, array2 with result from id2. array1 的结果来自 id1,array2 的结果来自 id2。 but instead I get 1 array with result from both id merged together.但相反,我得到了 1 个数组,其中两个 id 的结果合并在一起。

How to make it so the array is seperated.如何使数组分开。

您可以通过这样做获得二维数组:

$result[id] = $this->model->run_some_query($id);

Is $this->model->run_some_query($id) returning an array reference, maybe? $this->model->run_some_query($id)返回数组引用,也许? http://php.net/manual/en/language.references.php http://php.net/manual/en/language.references.php

you can try this code on your loop statement您可以在循环语句中尝试此代码

foreach($array as $value){
  $id = $value->id;
  $result[] = $this->model->run_some_query($id);

}
var_dump($result);

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

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