将术语用引号括起来并用逗号分隔的字符串转换为 PHP 中的子数组数组
Transform string with term enclosed in quotes and separated by commas into array of subarrays in PHP
我有一个 Mysql 数据库,其中一个字段包含用逗号分隔的引号中的一串术语,我需要将该字段转换为一个或多个数组,并向每个术语添加一些信息,这些信息将用于后续更新,如下图。
字段值:“个人、群体和人口”,“多样性和包容性”,“保护”
结果是一个或多个这样的数组:
“部分”:[
{
"term": "个人、群体和人口",
“定义”: ””
},
{
"term": "多元化和包容性",
“定义”: ””
},
{
“术语”:“保护”,
“定义”: ””
}
],
谢谢
尝试使用 json-decode 将其转换为 PHP 变量。
您可以使用 preg_split 获取数组中的项目。
<?php
$str = '"Individuals, groups and populations","Diversity and inclusion","Protection"';
$pattern = '/\"*\"/';
$components = preg_split($pattern, $str,-1,PREG_SPLIT_NO_EMPTY);
$components = array_diff($components,array(','));
print_r($components);
$a = array();
foreach($components as $c){
$array = null;
$array['term'] = $c;
$array['definition'] = "";
array_push($a,json_encode($array));
}
print_r($a);
?>
我有一个 Mysql 数据库,其中一个字段包含用逗号分隔的引号中的一串术语,我需要将该字段转换为一个或多个数组,并向每个术语添加一些信息,这些信息将用于后续更新,如下图。
字段值:“个人、群体和人口”,“多样性和包容性”,“保护”
结果是一个或多个这样的数组:
“部分”:[ { "term": "个人、群体和人口", “定义”: ”” }, { "term": "多元化和包容性", “定义”: ”” }, { “术语”:“保护”, “定义”: ”” } ],
谢谢
尝试使用 json-decode 将其转换为 PHP 变量。
您可以使用 preg_split 获取数组中的项目。
<?php
$str = '"Individuals, groups and populations","Diversity and inclusion","Protection"';
$pattern = '/\"*\"/';
$components = preg_split($pattern, $str,-1,PREG_SPLIT_NO_EMPTY);
$components = array_diff($components,array(','));
print_r($components);
$a = array();
foreach($components as $c){
$array = null;
$array['term'] = $c;
$array['definition'] = "";
array_push($a,json_encode($array));
}
print_r($a);
?>