skip to Main Content

I have this array in PHP:

Array ( [0] => Array ( [time_book_start] => 11:30 ) 
        [1] => Array ( [time_book_start] => 9:00 ) 
       )

I just need to output 11:30 and 9:00 in this manner:

['11:30','9:00']

I have used json_encode, sprintf, implode etc without success. Please help me.

2

Answers


  1. The desired result doesn’t match the structure of your array, so first you need to change the array structure. Then you can encode it as JSON to get that formatted output.

    One way is to simply construct a new array by taking data from the original one:

    $arr = [["time_book_start" => "11:30"], ["time_book_start" => "09:00"]];
    $arr2 = [];
    
    foreach ($arr as $key => $val)
    {
        $arr2[] = $val["time_book_start"];
    }
    
    echo json_encode($arr2);
    

    Demo: https://3v4l.org/lF7LL


    However PHP also has a built-in function array_column() which can do the same job for you in this particlular scenario. It returns all the values from the named column in the array, in a single flat array structure:

    $arr = [["time_book_start" => "11:30"], ["time_book_start" => "09:00"]];
    
    $arr2 = array_column($arr, "time_book_start");
    
    echo json_encode($arr2);
    

    Demo: https://3v4l.org/VgF4Q

    Login or Signup to reply.
  2. You can use the array_map function in PHP.

    $array = [["time_book_start" => "11:30"], ["time_book_start" => "9:00"]]; // Your array here
    $time_book_start_array = array_map(function($item) { return $item["time_book_start"]; }, $array); // The $time_book_start_array contains your desired array.
    

    Or more shortly you can also use array_column function.

    $array = [["time_book_start" => "11:30"], ["time_book_start" => "9:00"]]; // Your array here
    $time_book_start_array = array_column($array, "time_book_start"); // The $time_book_start_array contains your desired array.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search