Search code examples
phpsortingphalcon

foreach sort results from database


I have 9 blocks, and I want sort it by last news added. I have code:

$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;
    }

How I can order by last records of:

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

Results in my array:

itemsps


Solution

  • I dont know your DB but i bet you can achive your goal with just one query and some tables joins. Please take some time to understand phalcon models

    If you still want to use that format you could use array_multisort() to sort the array:

        $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);