Sorting Multi Dimensional Array in CodeIgniter 4

Reading Time: 7 minutes
4,176 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.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the application.


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.

//...

$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.

$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.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more