从数组中删除搜索结果

时间:2013-03-24 19:13:10

标签: php arrays multidimensional-array

我有一段PHP代码可以生成一系列搜索结果(来自Facebook API搜索)。

是否可以包含一个超链接/按钮,单击该按钮时,从阵列中删除该项并刷新以显示新数组?

我认为我将使用unset()删除该项目。

这是我的代码:

foreach ($search['data'] as $key => $list) {
   echo "<li><dt>Name:</dt>" . "<dd>" . $list['name'] . "</dd>\n";

   $gender = $facebook->api('/'.$list['id']);
   echo "<dt>Gender:</dt>" . "<dd>".ucfirst($gender['gender'])."</dd>\n";
   echo "   <a href='fb2.php?fbid=" .$list['id']. "'><img src='https://graph.facebook.com/".$list['id']."/picture?type=normal' /></a>\n";
   echo "<a href='remove.php?id= ????? ";
   echo "</li>";
    } 
    echo"</ol>"; 

2 个答案:

答案 0 :(得分:2)

我知道你没有提到Javascript作为一个选项,但如果只是在前端我将使用jQuery如下:

HTML文件中的

<script url="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>

<ol id="facebook-tags">

<?php
    foreach ($search['data'] as $key => $list) {
        echo "<li><dt>Name:</dt>" . "<dd>" . $list['name'] . "</dd>\n";
        $gender = $facebook->api('/'.$list['id']);
        echo "<dt>Gender:</dt>" . "<dd>".ucfirst($gender['gender'])."</dd>\n";
        echo "   <a href='fb2.php?fbid=" .$list['id']. "'><img src='https://graph.facebook.com/".$list['id']."/picture?type=normal' /></a>\n";
        echo "<a class="remove">Remove</a>";
        echo "</li>";
    } 
?>

</ol>

<script>
    $('#facebook-tags').delegate('a.remove', 'click', function() {
        $(this).closest('li').remove();
    });
</script>

答案 1 :(得分:2)

chrislondon给了你如何在客户端删除的建议。 但是如果你想在PHP端删除一些,可以这样做:

foreach ($search[ 'data' ] as $key => $list ) {
    if( $_GET[ 'id' ] == $key ){
//use unset only if you store $search[ 'data' ] in session or some, to remove it totally from results
//        unset( $search[ 'data' ][ $key ] );
        continue;
    }

    echo "<li><dt>Name:</dt>" . "<dd>" . $list[ 'name' ] . "</dd>\n";

    $gender = $facebook -> api( '/' . $list[ 'id' ] );
    echo "<dt>Gender:</dt>" . "<dd>" . ucfirst( $gender[ 'gender' ] ) . "</dd>\n";
    echo "<a href='fb2.php?fbid=" . $list[ 'id' ] . "'>
        <img src='https://graph.facebook.com/" . $list[ 'id' ] . "/picture?type=normal' /></a>\n";
    echo "<a href='remove.php?id=$key ";
    echo "</li>";
}
echo"</ol>";