Categories
Code Area PHP Programming Tips and Tricks Tools and Technologies

Array Chunk based on Key Value in PHP

Sometimes programmer needs to chunk or grouping array based on the array key value. Look at the below code snippet, here I have a multidimensional array, and I want to group all same elements of each category.

OUTPUT:

array (
  'php' => 
  array (
    0 => 
    array (
      'category' => 'php',
      'post_id' => 100,
    ),
    1 => 
    array (
      'category' => 'php',
      'post_id' => 102,
    ),
    2 => 
    array (
      'category' => 'php',
      'post_id' => 104,
    ),
  ),
  'html' => 
  array (
    0 => 
    array (
      'category' => 'html',
      'post_id' => 101,
    ),
    1 => 
    array (
      'category' => 'html',
      'post_id' => 104,
    ),
  ),
  'js' => 
  array (
    0 => 
    array (
      'category' => 'js',
      'post_id' => 103,
    ),
  ),
)
Categories
Code Area PHP Programming

Search Value from Multi Dimension Array

Here is simple example of searching specific value from a multi dimension array.

Categories
Code Area PHP

Sorting Array by using Linear Algorithm

Sorting Array by using Linear Algorithm are given below.

CODE:

<?php
/**
 * Created by JetBrains PhpStorm.
 * User: RANA
 * Date: 6/13/13
 * Time: 4:23 PM
 * To change this template use File | Settings | File Templates.
 */
class LinearAlgorithm
{
    private  $MyArray;

    /**
     * @param $SortingArray
     */
    Public function __construct($SortingArray){
        $this->MyArray = $SortingArray;
    }

    /**
     * @return mixed as a Sorting the array Element.
     */
    public function SortingNumber(){
        foreach($this->MyArray as $Element => $value){
            $PostElement = $Element + 1;
            while (($PostElement < count($this->MyArray) && ($this->MyArray[$PostElement] < $this->MyArray[$Element])))
            {
                $Temp = $this->MyArray[$Element];
                $this->MyArray[$Element] = $this->MyArray[$PostElement];
                $this->MyArray[$PostElement] = $Temp;

                if ($Element > 0)
                {
                    $Element--;
                }
                $PostElement--;
            }
        }
        return $this->MyArray;
    }

    /**
     * @param Output the output.
     */
    public function GetResult(){
        foreach($this->SortingNumber() as $Result){
            echo $Result."<br/>";
        }
    }
}

$Array = array(5,10,266,255,1656,36,66,1,5665);
$Object = new LinearAlgorithm( $Array);
$Object->GetResult();

 

OUTPUT:

1
5
10
36
66
255
266
1656
5665