我有一个php
数组,如下所示:
array:7 [▼
"id" => 13
"agent_id" => 1
"reserved_by" => 1
"vehicle_type" => "["Bus","Car"]"
"no_of_vehicle" => "["2","1"]"
"created_at" => "2017-06-13 05:46:49"
"updated_at" => "2017-06-13 05:46:49"
]
此处,vehicle_type
和no_of_vehicle
采用json_encode
格式。在上面的例子中,
按json_decode
我可以得到两个这样的数组
汽车类型
dd(json_decode($data->vehicle_type));
array:2 [▼
0 => "Bus"
1 => "Car"
]
no_of_vehicle
dd(json_decode($data->no_of_vehicle));
array:2 [▼
0 => "2"
1 => "1"
]
现在,我想要的是创建一个车辆类型和数字等于1的关联数组。
array:3 [▼
Bus => "1"
Bus => "1"
Car => "1"
]
因为你所说的所有因为独特的钥匙而不可能。但是,是否可以使用嵌套的类似数组:
array:3 [▼
array:1 [▼
Bus => "1"
]
array:1 [▼
Bus => "1"
]
array:1 [▼
Bus => "1"
]
]
这对我来说没问题
不知道,我正在使用laravel 5.3
由于
答案 0 :(得分:2)
array:3 [▼
Bus => "1"
Bus => "1"
Car => "1"
]
这是不可能的,因为键必须是唯一的
你可以进入
["Bus", "Bus", "Car"]
或
["Bus" => 2, "Car" => 1]
回答更新的问题
你可以这样做:
$array = [
"id" => 13,
"agent_id" => 1,
"reserved_by" => 1,
"vehicle_type" => array("Bus", "Car"),
"no_of_vehicle" => array("2", "1"),
"created_at" => "2017-06-13 05:46:49",
"updated_at" => "2017-06-13 05:46:49",
];
$result = [];
foreach ($array["vehicle_type"] as $key => $vehicle) {
$num = intval($array["no_of_vehicle"][$key]);
for ($i = 1; $i <= $num; $i++) {
$result[] = array($vehicle => "1");
}
}
$result
将是:
array:3 [▼
0 => array:1 [▼
"Bus" => "1"
]
1 => array:1 [▼
"Bus" => "1"
]
2 => array:1 [▼
"Car" => "1"
]
]
答案 1 :(得分:0)
我会创建一个这样的数组:
array[
{
vehicle_type => 'Bus',
no_of_vehicle => 2,
},
{
vehicle_type => 'Car',
no_of_vehicle => 1,
}
]
或
array['Bus_1', 'Bus_2', 'Car_1']