Home  >  Article  >  Backend Development  >  laravel - php, why use objects? Can't I use an array instead?

laravel - php, why use objects? Can't I use an array instead?

WBOY
WBOYOriginal
2016-09-24 09:15:071329browse

Just like laravel orm, can't it be done by using the query builder?

Reply content:

Just like laravel orm, can't it be done by using the query builder?

Isn’t it normal for PHP to use arrays to save the result sets of SQL queries? Why do you say that arrays cannot be used?
PDO fetchAll returns an array:
$db->query('SELECT * FROM posts')- >fetchAll(PDO::FETCH_ASSOC);
PHP array operations are very flexible and can do many things, even things in SQL, such as sorting and grouping:

<code><?php
//奥运奖牌榜,依次按金牌,银牌,铜牌的数目进行降序排序.
header('Content-Type: text/plain; charset=utf-8');
$arr = array(
    '中国' => array(
        '金牌' => 8,
        '银牌' => 3,
        '铜牌' => 6,
    ),
    '俄罗斯' => array(
        '金牌' => 3,
        '银牌' => 6,
        '铜牌' => 3,
    ),
    '美国' => array(
        '金牌' => 6,
        '银牌' => 8,
        '铜牌' => 8,
    ),
    '澳大利亚' => array(
        '金牌' => 4,
        '银牌' => 0,
        '铜牌' => 4,
    ),
    '意大利' => array(
        '金牌' => 3,
        '银牌' => 4,
        '铜牌' => 2,
    ),

);

// 实现 ORDER BY
foreach($arr as $k => $v) {
    $sort['金牌'][$k] = $v['金牌'];
    $sort['银牌'][$k] = $v['银牌'];
    $sort['铜牌'][$k] = $v['铜牌'];
}
array_multisort(
    $sort['金牌'], SORT_DESC, 
    $sort['银牌'], SORT_DESC, 
    $sort['铜牌'], SORT_DESC, 
    $arr);
var_export($arr);

// 实现 GROUP BY (看看'金牌'字段都有哪些值)
$tmp = array();
foreach($arr as $k => $v) {
    if(in_array($v['金牌'], $tmp) === FALSE) {
        $tmp[] = $v['金牌'];
    }
}
var_export($tmp);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn