如何循环遍历数组并根据需要显示按钮

时间:2017-07-12 13:59:22

标签: php arrays codeigniter-3

req_sent数组由向其发送好友请求的ID组成。 req_pending数组由收到请求但尚未接受好友请求的ID组成。 nonfriends数组包含除登录人员ID之外的所有朋友ID。因此,通过使用if else,我正在检查非朋友[' id'] == req_sent(发送请求的朋友的ID)。同样我也在检查req_pending数组。但按钮不会根据需要显示在视图页面中。请帮忙。

<table class="table class table-bordered table-striped">
    <caption>Nonfriends list table</caption>
    <thead>
        <tr>
            <th>Alias</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
    <?php 
        $req_sent = array();
        foreach($request_sent as $request_sent_id)
        {
            $req_sent[] = $request_sent_id['id'];
        }

        $req_pending = array();
        foreach($request_pending as $request_pending_id)
        {
            $req_pending[] = $request_pending_id['id'];
        }

        print_r($nonfriends);


     //print_r($nonfriends);
    foreach($nonfriends as $nonfriend)
    {

            echo "<tr>";
            echo "<td>";
            echo $nonfriend["alias"];
            echo "</td>";
            echo "<td>"; 

            if($nonfriend['id'] == $req_sent) { ?>
            <button class="btn btn-danger"><a href="#"  data-toggle="modal" data-target="#myModal">Request Sent</a></button>
           <?php } 

            echo "</td>";
            echo "</tr>";

    }
    ?> 
    </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您可以将以下in_array应用于待处理,已发送和&amp;新请求

//print_r($nonfriends);
foreach($nonfriends as $nonfriend)
{

        echo "<tr>";
        echo "<td>";
        echo $nonfriend["alias"];
        echo "</td>";
        echo "<td>"; 

        if(in_array($nonfriend['id'], $req_pending)) { 
        ?>
            <button class="btn btn-danger"><a href="#"  data-toggle="modal" data-target="#myModal">Request Pending</a></button>
        <?php 
        } 
        elseif(in_array($nonfriend['id'], $req_sent)) { 
        ?>
            <button class="btn btn-danger"><a href="#"  data-toggle="modal" data-target="#myModal2">Request Sent</a></button>
        <?php 
        } else {
        ?>
            <button class="btn btn-danger"><a href="#"  data-toggle="modal" data-target="#myModal3">Send Request</a></button>    
        <?php
        }

        echo "</td>";
        echo "</tr>";

}