简体   繁体   中英

Transform string with term enclosed in quotes and separated by commas into array of subarrays in PHP

I have a Mysql database with one field that contains a string of terms in quotes separated by commas, I need to turn that field into an array or arrays and add to each term some information that will be updated in the future, as the example below.

field value: "Individuals, groups and populations","Diversity and inclusion","Protection"

Result it an array or arrays such:

"Partof": [ { "term": "Individuals, groups and populations", "definition": "" }, { "term": "Diversity and inclusion", "definition": "" }, { "term": "Protection", "definition": "" } ],

Thank you

Try use json-decode to converts it into a PHP variable.

You can use preg_split to get the items in array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM