仅在存在时显示数组

时间:2013-09-04 11:05:42

标签: php mysql arrays

我创建了一个页面,用户可以在其中查看数据库中输入的数据 我用过:

$select = "SELECT * FROM texts WHERE user='".$user."' ORDER BY date DESC, id DESC";
$result = mysql_query($select);
$array = array();
while($show = mysql_fetch_assoc($result))
{
$array[] = $show;
}
echo "<strong>".$array[0]['id']."</strong><br />";
echo "<strong>".$array[1]['id']."</strong><br />";
echo "<strong>".$array[2]['id']."</strong><br />";
echo "<strong>".$array[3]['id']."</strong><br />";
echo "<strong>".$array[4]['id']."</strong><br />";

代码有效,但有时我会返回少于10个值,有时甚至更多 如果我使用它并且我只有2个数组要返回,我得到:

Notice: Undefined offset: 2 in ownposts.php on line 15
Notice: Undefined offset: 3 in ownposts.php on line 16
Notice: Undefined offset: 4 in ownposts.php on line 17

如果存在$ array [4],如何回显 $ arrray [4] ['id] ? 我试过了:

$zero = $array[0];
if(!empty($zero))
{
echo "<strong>".$zero['id']."</strong><br />";
}
$four = $array[4];
if(!empty($four))
{
echo "<strong>".$five['id']."</strong><br />";
}

但不行,因为我除外并仍然返回注意:未定义的offsed:第17行的ownposts.php中的4

4 个答案:

答案 0 :(得分:3)

而不是你现在所做的,这个:

while($show = mysql_fetch_assoc($result))
{
$array[] = $show;
}
echo "<strong>".$array[0]['id']."</strong><br />";
echo "<strong>".$array[1]['id']."</strong><br />";
echo "<strong>".$array[2]['id']."</strong><br />";
echo "<strong>".$array[3]['id']."</strong><br />";
echo "<strong>".$array[4]['id']."</strong><br />";

为什么不在你找到它时只显示mysql发现的内容:

while($show = mysql_fetch_assoc($result))
  {
    echo "<strong>".$show['id']."</strong><br />";
  }

或者如果你有其他与数组相关的事情,而不是你向我们展示的代码,请在新创建的数组上使用循环,即foreach。

答案 1 :(得分:1)

foreach($array as $data){
echo '<strong>'.$data['id'].'</strong><br />';
}

答案 2 :(得分:0)

我按如下方式重写:

$i = 0;
while($show = mysql_fetch_assoc($result))
{
    $array[] = $show;
    if (isset($array[$i])) {
        echo "<strong>".$array[$i]['id']."</strong><br />";
    }
    $i++;
}

答案 3 :(得分:0)

在php中有功能可以检查,array_key_exists。 你可以检查一下, http://php.net/manual/en/function.array-key-exists.php

相关问题