Skip to content

Instantly share code, notes, and snippets.

@feryardiant
Last active August 29, 2015 14:23
Show Gist options
  • Save feryardiant/1a1b2d0275bcdfc212bf to your computer and use it in GitHub Desktop.
Save feryardiant/1a1b2d0275bcdfc212bf to your computer and use it in GitHub Desktop.
Array Order by

Example Usage

$data = [
  [ 'parent'=> 1, 'id' => 4, 'data' => 'empat', ], 
  [ 'parent'=> 4, 'id' => 2, 'data' => 'dua',   ], 
  [ 'parent'=> 0, 'id' => 3, 'data' => 'tiga'   ], 
  [ 'parent'=> 3, 'id' => 1, 'data' => 'satu'   ]
];

$sorted = array_orderby('id', 'parent', $data);
print_r($sorted);

Result

Array
(
  [0] => Array
    (
      [parent] => 0
      [id] => 3
      [data] => tiga
    )

  [1] => Array
    (
      [parent] => 3
      [id] => 1
      [data] => satu
    )

  [2] => Array
    (
      [parent] => 1
      [id] => 4
      [data] => empat
    )

  [3] => Array
    (
      [parent] => 4
      [id] => 2
      [data] => dua
    )
)
<?php
/**
* Ordering array
*
* @souce http://codepad.org/yPz2rTLQ
*/
function array_orderby($fieldId, $fieldParent, $data, $parentID = 0, &$result = [])
{
foreach ($data as $key => $value)
{
if ($value[$fieldParent] == $parentID)
{
array_push($result, $value);
unset($data[$key]);
$oldParent = $parentID;
$parentID = $value[$fieldId];
array_orderby($fieldId,$fieldParent, $data, $parentID, $result);
$parentID = $oldParent;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment