Sorting Multi Dimensional Array in CodeIgniter 4

Share this Article
Reading Time: 8 minutes
9 Views

Inside this article we will see sort multi dimensional array using usort() method of PHP. We will sort by using array value.

This will be interesting article to get the things in a very easy way. Step by step sorting multi dimensional array in codeigniter 4.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Connectivity

We need to create a database. For database we will use MySQL.

CREATE DATABASE codeigniter4_app;

Next, we need to connect with application.

Database Connectivity to Application

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi

Create Migration

Open project into terminal and run this spark command.

$ php spark make:migration CreateBooks

It has generated a file with name 2021-02-09-120132_CreateBooks.php at /app/Database/Migrations folder.

Open up the file and write this code into it.

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateBooks extends Migration
{
	public function up()
	{
		$this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => true,
                'auto_increment' => true,
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => false
            ],
            'author' => [
                'type' => 'VARCHAR',
                'constraint' => '100',
                'null' => false,
            ],
            'cost' => [
                'type' => 'INT',
                'constraint' => 100,
                'null' => false,
            ],
        'created_at datetime default current_timestamp',
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('books');
	}

	public function down()
	{
		$this->forge->dropTable('books');
	}
}

Next, we need to migrate this created migration into database.

$ php spark migrate

It will create a database table with name “books”.


Create Seeder

Back to terminal and run this spark command.

$ php spark make:seeder BookSeeder

It has generated a file with name BookSeeder.php at /app/Database/Seeds folder.

Open up the file and write this code into it.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use Faker\Factory;

class BookSeeder extends Seeder
{
	public function run()
    {
        for ($i = 0; $i < 10; $i++) { //to add 10 books. Change limit as desired
            $this->db->table('books')->insert($this->generateBooks());
        }
    }

    private function generateBooks(): array
    {
        $faker = Factory::create();
        return [
            'name' => $faker->name(),
            'author' => $faker->name(),
            'cost' => random_int(300, 800)
        ];
    }
}

Next, we need to seed test data into table

$ php spark db:seed BookSeeder

It will generate and insert 10 rows of fake data into “books” table.


Add Route

Open Routes.php file from /app/Config folder.

Add this route into it.

//.. Other routes

$routes->get("list-data", "Site::listdata");

Create Model

Back to terminal and run this spark command.

$ php spark make:model Book

It has generated a file with name Book.php at /app/Models folder.

Open up the file and write this code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

class Book extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'books';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Create Helper

Create a helper file with name custom_helper.php at /app/Helpers folder.

<?php

if(!function_exists("SortByBookName")){

    function SortByBookName($x, $y){

        return strcasecmp($x['name'], $y['name']);
    }
}

if(!function_exists("SortByBookCost")){

    function SortByBookCost($x, $y){

        return $x['cost'] - $y['cost'];
    }
}

Here, we have two functions created which is used to sort books data book name or book cost.

Helper name here is custom. _helper is the suffix added with file name which is naming convention for creating a helper file.


Create Controller & Application Testing

Back to terminal and run this spark command.

$ php spark make:controller Site

It has generated a file with name Site.php at /app/Controllers folder.

<?php

namespace App\Controllers;

use App\Models\Book; // Loading model

class Site extends BaseController
{
    public function listdata()
    {
        helper("custom"); // Loading helper
      
        $book_obj = new Book();

        $books = $book_obj->findAll();

        // Sorting books by name - SortByBookName() in helper file
        usort($books, "SortByBookName");
      
      	echo "<pre>";
        print_r($books);
    }
}

Open project into terminal and start development server.

$ php spark serve

URL: http://localhost:8080/list-data

public function listdata()
{
  helper("custom"); // Loading helper

  $book_obj = new Book();

  $books = $book_obj->findAll();

  // Sorting books by cost - SortByBookCost() in helper file
  usort($books, "SortByBookCost");

  echo "<pre>";
  print_r($books);
}

Back to browser and type this url

URL: http://localhost:8080/list-data

In case, if suppose we have Library for sorting methods. Then we need to call like this.

# Load Library to Controller

$object = new LibraryName();

usort($books, ($object, "SortByBookCost"));

We hope this article helped you to learn Sorting Multi Dimensional Array in CodeIgniter 4 in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment