PHP json foreach仅返回最后一条记录

时间:2015-05-11 07:24:22

标签: php mysql json foreach

Helo,我的json有问题,我正在为一个foreach做一个foreach ...不要问为什么

我的问题是foreach foreach( $result2 as $rowx )只返回最后一条记录。查询没问题,工作正常,它返回数据库中的2个字段,但只有最后一个是echo。#/ p>

请帮助。

 if(!$location){
    echo '{"locations":[';
    $query = $db->prepare("SELECT * FROM locations"); 
    $query->execute();
    $result = $query -> fetchAll();
    $num_rows = count($result);
           for ($x = 1; $x < $num_rows; $x++) {
    foreach( $result as $row ) { 
    $qer = "SELECT DISTINCT t.id_temp,f.id_fridge,l.id_location,t.id_sensor,f.denumire AS 'fridge_name',l.name AS 'location_name',l.address AS 'location_address',t.date,t.time,t.temp FROM fridges AS f,locations AS l,temperature AS t WHERE f.fk_location=l.id_location AND f.fk_id_sensor=t.id_sensor AND l.id_location='1' AND t.date='07/05/2015' ORDER BY t.id_temp DESC LIMIT 0,2";

    $query2 = $db->prepare($qer); 
    $query2->execute();
    $result2 = $query2 -> fetchAll();



    echo '{"location_name":"'.$row[1].'","nr_fridges":'.$row[2].',"fridge":';
    foreach( $result2 as $rowx ) { 

    }
    echo '{
    '.$rowx['fridge_name'].'

    }'; 

    echo '}';

    }
        echo "]}";
    exit; 
    }
    }

3 个答案:

答案 0 :(得分:2)

你在循环之外有<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/rl_rating" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" > <RatingBar android:id="@+id/ratingBar" android:layout_width="wrap_content" android:layout_height="78dp" style="@style/CustomRatingBar" /> </RelativeLayout> </LinearLayout> 个。

echo

答案 1 :(得分:0)

您的问题可能是因为您在循环之后使用$rowx['fridge_name'] 而不是在其中:

foreach( $result2 as $rowx ) { 

}
echo '{
'.$rowx['fridge_name'].'

}'; 

应该是:

foreach( $result2 as $rowx ) { 
  echo '{
  '.$rowx['fridge_name'].'
  }'; 
}

另请注意,现在您没有构建有效的json,因为对象需要一个键值对,其中字符串值以双引号"引用。

但是,你不应该手动构建json,而应该构建一个你需要的表单数组,最后你会这样做:

echo json_encode($your_array);

答案 2 :(得分:0)

foreach( $result2 as $rowx ) { //foreach begin

    } //foreach end

您的echo位于foreach循环之外。

试试这个,

foreach( $result2 as $rowx ) { 
    echo '{
    '.$rowx['fridge_name'].'
    }';
}