Showing posts with label How to shift php array key pair value to top or bottom. Show all posts
Showing posts with label How to shift php array key pair value to top or bottom. Show all posts

Tuesday, March 1, 2016

How to shift php array key pair value to top or bottom

MOVE KEY VALUE PAIR TO THE TOP/BOTTOM OF AN ARRAY

<?php
class demo{
   public function arratData(){
      $myArray= array (
                 'bk101' => array (
                                'author' => 'Gambardella, Matthew',
                                'title' => 'XML Developer\'s Guide',
                                'genre' => 'Computer',
                                'price' => '44.95',
                                'publish_date' => '2000-10-01',
                                'id' => 'bk101'
                                  ),
                 'bk102' => array (
                                'id' => 'bk102',
                                'author' => 'Ralls, Kim',
                                'title' => 'Midnight Rain',
                                'genre' => 'Fantasy',
                                'price' => '5.95',
                                'publish_date' => '2000-12-16',
                                'description' => 'A former architect battles corporate zombies...',
                                  ),
                        );
 
    echo '<pre>Actual Array set <br />';
    print_r($myArray);
 
    // call the function move_to_top
    // i want ID of "bk101" should be at top
 
    $top = $this->move_to_top($myArray['bk101'],'id');
 
    echo '<h4>ID of "bk101 will be at top which is at bottom in actual array"</h4>';
    print_r($top);
 
 
    // Now call the function move_to_bottom
    // i want ID of "bk102" should be at bottom which is at top right now
 
    $bottom = $this->move_to_bottom($myArray['bk102'],'id');
 
   echo '<h4>ID of "bk102 will be at bottom which is at top in actual array"</h4>';
    print_r($bottom);
 
 
 
 
   }
 
    public  function move_to_top(&$array, $key) {
        $temp = array($key => $array[$key]);
        unset($array[$key]);
        return $array = $temp + $array;
    }

    public  function move_to_bottom(&$array, $key) {
         
            $temp = array($key => $array[$key]);
            unset($array[$key]);
            return $array = $array + $temp;
    }
}

$a=new demo;
$show_data=$a->arratData();
echo $show_data;
?>

Output





Download File