获取二维数组中的数据

时间:2013-12-09 07:46:39

标签: php mysql arrays codeigniter

你好这可能看起来很简单,但我很震惊......在我的应用程序中,我得到的数组就像

Array
(
[0] => Array
    (
        [home_id] => 1
        [distance] => 12
    )
[1] => Array
    (
        [home_id] => 3
        [distance] => 14
    )


[2] => Array
    (
        [home_id] => 94
        [distance] => 1.679713069
    )
    .
    .
    .
    .

)

我的桌子看起来像

home_id  | home_name

1        |   My home 1

2        |   My home 2

3        |   My home 3

从这个数组中我将获得数据库表中的home_id。那么我如何得到结果细节,其中包括home_name和第一个数组的距离,可能就像

home_name        |  distance
 ___________________________
My home 1        |   0.562620830044

My home 3        |   14

提前谢谢

3 个答案:

答案 0 :(得分:2)

循环遍历数组并使用home_name查询 -

从数据库中获取codeigniter active record
foreach($yourArray as $row)
{
   $id = $row['home_id'];
   $distance = $row['distance'];
   $db_result = $this->db->get_where('yourtable', array('home_id' => $id));
   if($db_result && $db_result->num_rows() > 0){
    $result = $db_result->row();
    $home_name = $result->home_name;
   }

}

答案 1 :(得分:1)

如果你不能JOIN一个查询中的两个表并且必须使用该数组,那么你可以这样做:

foreach($yourArray as $home)
{
   $id=$home["home_id"];
   $distance=$home["distance"];
   $id=intval($id);
   $sql="SELECT home_name FROM yourTable WHERE home_id=$id";   // execute this query to get name
}

答案 2 :(得分:0)

From this array i will get the home_id which is in database table. So How can i get the result details which includes the home_name and the distance from the first array which might be like

如果您希望使用从主数组中获取的home details从表home_details_table获取id,请将home_name中的字段home_details_table替换为home_id One to Many并将这两个表链接为home_id | home_name 1 | My home 1 2 | My home 2 3 | My home 3 关系。

home_table:

home_id  |  distance
1        |   0.562620830044

3        |   14

home_detail_table:

JOIN

然后使用foreach($mainArray as $home) { $id = $home["home_id"]; $sql="SELECT h.home_id, h.home_name, d.home_distance FROM home_table h JOIN home_details_table d ON h.home_id = d.home_id WHERE h.home_id = ".$id; // with this query you will have the name and distance of the given home id. } ,您将可以执行以下操作:

{{1}}