user7596515
user7596515

Reputation:

How to access specific values for specific keys in php array

I want to show specific values according to specific keys in a array.

there are some keys which are fetched from database then i want to show its meaningful values like:

array('12_01'=>'12:00 - 01:00','01_02'=>'01:00 - 02:00');

here is code:

<?php echo implode(',',$selected_hours); ?>

And here is Array:

$hourshow = array('12_01'=>'12:00 - 01:00',
          '01_02'=>'01:00 - 02:00',
          '02_03'=>'02:00 - 01:03',
          '03_04'=>'03:00 - 04:00', 
          '04_05'=>'04:00 - 05:00',
          '05_06'=>'05:00 - 06:00',
          '06_07'=>'06:00 - 07:00',
          '07_08'=>'07:00 - 08:00',
          '07_09'=>'08:00 - 09:00',
          '09_10'=>'09:00 - 10:00',
          '10_11'=>'10:00 - 11:00',
          '11_12'=>'11:00 - 12:00',
          '12_13'=>'12:00 - 13:00',
          '13_14'=>'13:00 - 14:00',
          '14_15'=>'14:00 - 15:00',
          '15_16'=>'15:00 - 16:00',
          '16_17'=>'16:00 - 17:00',
          '17_18'=>'17:00 - 18:00',
          '18_19'=>'18:00 - 19:00',
          '19_20'=>'19:00 - 20:00',
          '20_21'=>'20:00 - 21:00',
          '21_22'=>'21:00 - 22:00',
          '22_23'=>'22:00 - 23:00',
          '23_24'=>'23:00 - 24:00',
         );

Upvotes: 0

Views: 81

Answers (4)

Mandip Vora
Mandip Vora

Reputation: 309

    $keys =  array('12_01','01_02','02_03','03_04','04_05','05_06','06_07','07_08','08_09','09_10','10_11','11_12');
    $result = array();
    foreach($keys as $value){
        $val = explode('_',$value);

        $result[$value] = $val[0].':00 - '.$val[1].':00';

    }
    echo '<pre>';print_r($result);exit;

You can try with this code. You will getting result in result array.

Upvotes: 2

lazyCoder
lazyCoder

Reputation: 2561

@Ashish Vyas Simply do it like below

<?php
    $youKeysFetchedFromDb = array("12_01", "01_02"); //suppose

    foreach($youKeysFetchedFromDb as $value){
        echo $hourshow[$value];
    }

Upvotes: 0

Vini
Vini

Reputation: 626

Dont know if I get your question correctly, but this should be what you are looking for array_intersect_key($hourshow, array_flip($yourWantedHoursArray));

Upvotes: 0

mehulmpt
mehulmpt

Reputation: 16587

Use ksort():

$hourshow = array(...);
ksort($hourshow);
// $hourshow is now sorted according to key.

Upvotes: 0

Related Questions