user1765369
user1765369

Reputation: 1395

Removing a search result from an array

I have a piece of PHP code which produces an array of search results (from a Facebook API search).

Would it be possible to include a hyperlink/button that, when clicked, removed that item from the array and refreshed to display the new array?

I gather that I would be using unset() to remove the item.

Here is the code I have:

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>"; 

Upvotes: 1

Views: 94

Answers (2)

chrislondon was give you advice how to remove at at client-side. But if you want to delete some at PHP side, it can be done some like this:

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>";

Upvotes: 2

chrislondon
chrislondon

Reputation: 12031

I know you don't mention Javascript as an option but if it's only on the front end I would use jQuery as follows:

in HTML file:

<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>

Upvotes: 2

Related Questions