foreach 从数据库中排序结果

foreach sort results from database

我有 9 个区块,我想按最后添加的新闻排序。 我有代码:

$projects = Projects::find(['conditions' => 'active = 1', 'order' => 'id DESC']);
    $itemsps = [];
    foreach($projects as $project) {
        if(!$project->{'link_' . $lang. ''}) continue;
        $itemsp['title_md'] = $project->title_md;
        $itemsp['title_ru'] = $project->title_ru;
        $itemsp['link'] = 'http://'.$_SERVER['SERVER_NAME']. '/' . $lang . '/' . $project->{'link_' . $lang. ''};
        $category = Categories::findFirst('alias = ' . "'$project->link_md'" . ' OR alias_ru = ' . "'$project->link_ru'");
        $lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();

        if($lastCat === false) continue;

        $lastImage = 'uploads/' . $lastCat['news_id'] . '.jpg';

        $itemsp['image'] = $lastImage;

        $itemsps[] = $itemsp;
    }

我如何按以下的最后记录订购:

$lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();

我的数组中的结果:

itemsps

我不知道你的数据库,但我敢打赌你可以通过一个查询和一些表连接来实现你的目标。 请花点时间了解一下phalcon models

如果您仍想使用该格式,可以使用 array_multisort() 对数组进行排序:

    $projects = Projects::find(['conditions' => 'active = 1', 'order' => 'id DESC']);
    $itemsps = [];
    foreach($projects as $project) {
        if(!$project->{'link_' . $lang. ''}) continue;
        $itemsp['title_md'] = $project->title_md;
        $itemsp['title_ru'] = $project->title_ru;
        $itemsp['link'] = 'http://'.$_SERVER['SERVER_NAME']. '/' . $lang . '/' . $project->{'link_' . $lang. ''};
        $category = Categories::findFirst('alias = ' . "'$project->link_md'" . ' OR alias_ru = ' . "'$project->link_ru'");
        $lastCat = NewsCategories::find('categories_id = ' . $category->id)->getLast();

        $itemsp['lastCat'] = $lastCat; //ADD THIS

        if($lastCat === false) continue;

        $lastImage = 'uploads/' . $lastCat['news_id'] . '.jpg';

        $itemsp['image'] = $lastImage;

        $itemsps[] = $itemsp;
    }

    //ADD THE CODE BELOW

    $lastCat_array = array();
    foreach ($itemsps as $key => $row)
    {
        $lastCat_array[$key] = $row['lastCat'];
    }
    array_multisort($lastCat_array, SORT_DESC, $itemsps);

    print_r($itemsps);