Pecooou
Pecooou

Reputation: 137

Convert strings to associative array

I have five strings:

$array_key = "f_name, f_qty, f_price, f_cur_date";  

$food_name = "Meal for 2, Four Seasons Pizza, Lunch Deal, Pepsi";
$food_qty = "1, 3, 5, 7";
$food_price = "10, 30, 50, 70";
$food_userId = "1, 2, 3, 4";

I need some array like this:

Array (
  [0] => Array (
    [f_name] => Meal for 2
    [f_qty] => 1
    [f_price] => 10
    [f_cur_date] => 1
) 
[1] => Array (
    [f_name] => Four Seasons Pizza
    [f_qty] => 3
    [f_price] => 30
    [f_cur_date] => 2
) 
[2] => Array (
    [f_name] => Lunch Deal
    [f_qty] => 5
    [f_price] => 50
    [f_cur_date] => 3
)
[3] => Array (
    [f_name] => Pepsi
    [f_qty] => 7
    [f_price] => 70
    [f_cur_date] => 4
))

I convert strings to array with "explode":

$array_key_parts = explode(",",$array_key);
$food_name_parts = explode(",",$food_name);
$food_qty_parts = explode(",",$food_qty);
$food_price_parts = explode(",",$food_price);
$food_price_parts = explode(",",$food_price);

But don't know how to customize it further.

Basically, I'm getting this strings from query GROUP_CONCAT to use it in fullcalendar.js.

Upvotes: 0

Views: 55

Answers (1)

Hardik Solanki
Hardik Solanki

Reputation: 3195

You can make an array using array_map function like below :

$food_name_parts = explode(",",$food_name);
$food_qty_parts = explode(",",$food_qty);
$food_price_parts = explode(",",$food_price);
$array_key_parts = explode(",",$array_key);


$myarray = array_map(function ($f_name, $f_qty, $f_price) {
    return compact('f_name','f_qty','f_price');
}, $food_name_parts, $food_qty_parts, $food_price_parts);

echo "<pre>";
print_r($myarray);

Upvotes: 3

Related Questions