以更易读的方式过滤和打印数组

时间:2018-12-17 07:45:11

标签: php arrays

$sql = "select * from banners where bgroup > ''";
$st = $db->prepare($sql);
$st->execute();
$data = $st->fetchAll();
print_r($data);

结果(多维数组):

Array ( 
    [0] => Array ( 
            [id] => 59 
            [0] => 59 
            [date] => 2018-11-23 23:44:47 
            [1] => 2018-11-23 23:44:47 
            [src] => banners/5b5ccafff3f6a.jpg 
            [2] => banners/5b5ccafff3f6a.jpg 
            [name] => abc 
            [3] => abc 
    ) 
    [1] => Array... 
    [2] => Array...

我想过滤上面的内容-仅获取name = abc的那些子数组,并在不使用索引的情况下打印它们,并用新行分隔。

赞:

Array(
    Array{
        [id] => 59
        [date] => 2018-11-23 23:44:47

有帮助吗?

2 个答案:

答案 0 :(得分:1)

方法1:  修改您的sql查询,使其如下所示:

$sql = "select * from banners where name='abc' AND bgroup > ''";

方法2(效率不如上面的一种):

$newArr = [];

foreach($results as $result)
{
    if($result['name'] == 'abc')
    {
        $newArr[] = $result;   
    }
}

echo "<pre>";
print_r($newArr);

答案 1 :(得分:1)

您需要更改查询以及获取模式才能直接获得所需的输出:-

$st = $db->prepare("SELECT * from banners WHERE name = ? AND bgroup > ''");
$st->execute(array('abc'));
$data = $st->fetchAll(PDO::FETCH_ASSOC);
print_r($data);

注意:-正确,完整地使用prepared statements

参考:-{PDOStatement::fetchAll