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

Time:12-18

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

CodePudding user response:

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

CodePudding user response:

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