Laravel 5.2 - 将 json 键值转换为数组
Laravel 5.2 - convert json key values to array
我有以下 json 对象:
{"keywords": "foo", "industries":"1,37","contractTypes":"1"}
如何将以下键值转换为数组,如下所示:
{"keywords": "foo", "industries": ["1", "37"], "contractTypes": ["1"]}
所以基本上我想遍历对象,如果 属性 industries
和 contractTypes
存在且不为空,则将值转换为数组。
定义要转换为数组的属性列表
$array_properties = ['industries', 'contractTypes'];
解码JSON
$object = json_decode($json);
迭代您定义的属性并将每个属性转换为数组(如果它存在于对象上)。
foreach ($array_properties as $property) {
if (isset($object->$property)) {
$object->$property = explode(',', $object->$property);
}
}
如果需要,您可以稍后将对象重新编码为 JSON。
$object = json_encode($object);
赚钱
我有以下 json 对象:
{"keywords": "foo", "industries":"1,37","contractTypes":"1"}
如何将以下键值转换为数组,如下所示:
{"keywords": "foo", "industries": ["1", "37"], "contractTypes": ["1"]}
所以基本上我想遍历对象,如果 属性 industries
和 contractTypes
存在且不为空,则将值转换为数组。
定义要转换为数组的属性列表
$array_properties = ['industries', 'contractTypes'];
解码JSON
$object = json_decode($json);
迭代您定义的属性并将每个属性转换为数组(如果它存在于对象上)。
foreach ($array_properties as $property) { if (isset($object->$property)) { $object->$property = explode(',', $object->$property); } }
如果需要,您可以稍后将对象重新编码为 JSON。
$object = json_encode($object);
赚钱