将字符串转换为关联数组

时间:2017-04-10 12:37:32

标签: php arrays

我有五个字符串:

$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";

我需要这样的数组:

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
))

我将字符串转换为数组" 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);

但不知道如何进一步定制它。

基本上,我从查询GROUP_CONCAT获取此字符串以在fullcalendar.js中使用它。

1 个答案:

答案 0 :(得分:3)

您可以使用array_map函数制作数组,如下所示:

$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);