Foreach在foreach?显示不正确的数据

时间:2016-10-02 14:07:14

标签: php mysql foreach

我有2张桌子。 t1+--------+---------------+--------------+ | mid | name | desc | +---------------------------------------+ | 1 | Fris | Helo | | 2 | Kenn | Wow! | | 3 | Henny | CCC | +---------------------------------------+

t2数据如下:

+--------+---------+----------------+
| tid    | mid     | tcode          |
+-----------------------------------+
| 1      | 1       | 1              |
| 2      | 1       | GG             |
| 3      | 1       | TTTTTT!        |
+-----------------------------------+

$xzdtall = DB::fetch_all("SELECT * FROM t1 ORDER BY mid ASC"); foreach($xzdtall as $xzdt){ $testing = DB::fetch_all("SELECT * FROM t2 WHERE mid = $xzdt['mid'] ORDER BY tid ASC"); foreach($testing as $test){ $testlist[] = $test; } $xzdtlist[] = $xzdt; } 数据如下:

#my looping
<!--{loop $xzdtlist $xzdt}-->
<div>$xzdt[name] <!--{loop $testlist $test}--><b>$test[tcode]</b><!--{/loop}--></div>
<!--{/loop}-->

现在我的php编码是这样的:

<div>Fris <b>1</b><b>GG</b><b>TTTTTT!</b></div>
<div>Kenn <b>1</b><b>GG</b><b>TTTTTT!</b></div>
<div>Henny <b>1</b><b>GG</b><b>TTTTTT!</b></div>

现在我的循环如下:

Kenn

我的最终结果:

Henny

实际上我需要它是这样的,因为mid<div>Fris <b>1</b><b>GG</b><b>TTTTTT!</b></div> <div>Kenn</div> <div>Henny</div> &#39; s "ios_sound": "sound.wav"不在t2内:

vision.cameraMode = PBJCameraMode.Video
vision.audioBitRate = 44
vision.cameraOrientation = PBJCameraOrientation.Portrait
vision.focusMode = PBJFocusMode.ContinuousAutoFocus
vision.outputFormat = PBJOutputFormat.Standard
vision.videoRenderingEnabled = true
vision.additionalCompressionProperties = [AVVideoProfileLevelKey : AVVideoProfileLevelH264Baseline30]
vision.videoBitRate = 1
vision.startVideoCapture()

1 个答案:

答案 0 :(得分:2)

$testlist变量对每个$xzdt都有不同的值,所以你应该循环:

$xzdtall = DB::fetch_all("SELECT * FROM t1 ORDER BY mid ASC");
foreach ($xzdtall as $xzdt){
    // empty $testlist
    $testlist = array();
    $testing = DB::fetch_all("SELECT * FROM t2 WHERE mid = $xzdt['mid'] ORDER BY tid ASC");
    foreach($testing as $test){
        $testlist[] = $test;
    }

    // add `$testlist` to $xzdt
    $xzdt['t2s'] = $testlist;

    $xzdtlist[] = $xzdt;
}

然后在你的模板中(不知道它是什么引擎)这样的东西应该有效:

<!--{loop $xzdtlist $xzdt}-->
<div>$xzdt[name] <!--{loop $xzdt[t2s] $test}--><b>$test[tcode]</b><!--{/loop}--></div>
                                 ^ notice variable here
<!--{/loop}-->

此外,您还可以测试$xzdt[t2s]是否为空。

最后,我建议您了解mysql JOIN并使用JOIN的单个查询替换循环查询。