否则,如果不将查询放入foreach循环,我如何才能获得name
菲律宾比索:

$material_decode=json_decode($materials['materials']);
foreach($material_decode as $material_id=>$material_value)
{
    $forge_materials=mysql_fetch_assoc(mysql_query('SELECT `name` FROM `forging_materials` WHERE `id`='.$material_id.' LIMIT 1'));
    echo '<tr>'.
        '<td>'.
            $forge_materials['name'].
        '</td>'.
        '<td>'.
            number_format($material_value).
        '</td>'.
    '</tr>';
}

$material_decode(forge_material_id=>材料值):
stdClass Object
(
    [2] => 25
    [4] => 32
    [5] => 23
)

最佳答案

您可以使用循环外的WHERE同时获取所有需要的记录。这样只需要一个查询。
这对你有用:

$material_decode = json_decode($materials['materials'], true);
$forge_materials = mysql_query('SELECT `id`, `name` FROM `forging_materials` WHERE `id` IN ( '. implode(',', array_keys($material_decode)) .')');

while($row = mysql_fetch_assoc($forge_materials))
{
    echo '<tr>'.
      '<td>'.
        $row['name'].
      '</td>'.
      '<td>'.
        number_format($material_decode[$row['id']]).
      '</td>'.
    '</tr>';
}

请记住,mysql_u方法已经被弃用,现在建议您改用PDO或mysqli_u方法。您可以在文档中阅读更多内容:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/ref.pdo-mysql.php

09-25 18:36
查看更多