我正在拉丁语网站上工作,以这种方式保存字符串中的一些信息:
nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is
我想将此信息转换为这样的数组
array(
'nominative'=>array(
0=>array('us','a','um')
),
'genitive'=>array(
0=>'i'
)
'dative'=>array(
1=>'is'
)
'ablative'=>array(
1=>'is'
)
)
我目前的代码如下所示
//turn into array for each specification
$specs=explode(';',$specificities);
foreach($specs as $spec):
//turn each specification into a consecutive array
$parts=explode(':',$spec);
//turn multiple value into array
foreach($parts as &$value)
if(strpos($value,',')!==false)
$value=explode(',',$value);
//imbricate into one other
while(count($parts)!==1):
$val=array_pop($parts);
$key=array_pop($parts);
if(is_array($key)):
foreach($key as $k)
$parts[$k]=$val;
else:
$parts[$key]=$val;
endif;
endwhile;
endforeach;
我被困住了。帮助
编辑:感谢大家的快速回复! 我更喜欢的回应来自CaCtus。我修改它以增加灵活性,但它是最有用的。
对于有兴趣的人,这是新代码:
$parts=explode(';','nominative:0:er,ra,rum;genitive:0:i;dative,ablative:1:is;root:r;');
if(!empty($parts)&&!empty($parts[0])):
foreach($parts as $part):
$subpart=explode(':',$part);
$keys=explode(',',$subpart[0]);
foreach($keys as $key):
@$vals=(strpos($subpart[2],',')!==false)
?explode(',',$subpart[2])
:$subpart[2];
$final=(is_null($vals))
?$subpart[1]
:array($subpart[1]=>$vals);
endforeach;
endforeach;
endif;
答案 0 :(得分:0)
$string = 'nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is';
$finalArray = array();
// Separate each specification
$parts = explode(';', $string);
foreach($parts as $part) {
// Get values : specification name, index and value
$subpart = explode(':', $part);
// Get different specification names
$keys = explode(',', $subpart[0]);
foreach($keys as $key) {
if (preg_match('#,#', $subpart[2])) {
// Several values
$finalValues = explode(',', $subpart[2]);
} else {
// Only one value
$finalValues = $subpart[2];
}
$finalArray[$key] = array(
$subpart[1] => $finalValues
);
}
}
答案 1 :(得分:0)
有点简单的工作吗?
function multiexplode($ delimiters,$ string){
$ready = str_replace($delimiters, $delimiters[0], $string); $launch = explode($delimiters[0], $ready); return $launch; }
$ input =" 0:us,a,um; genitive:0:i; dative,ablative:1:is&#34 ;;
$ explosion = multiexplode(array(",",":",";"),$ input);
$ test = array( '主格' = GT;阵列(0 =>阵列($分解[1],$分解[2],$分解[3])), $分解[4] =>阵列(0 => $分解[6]), $分解[7] =>阵列(1 => $分解[10]), $ explosion [8] => array(1 => $ explosion [10]));
的print_r($测试);
答案 2 :(得分:0)
另一种选择:
$specificities = "nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is";
$specificities = trim($specificities, ";") . ";"; //mandatory a trailing ;
$pattern = "/(?<types>[a-z\,]+):(?<ids>\d):(?<values>.*?);/";
preg_match_all($pattern, $specificities, $matches, PREG_SET_ORDER);
$result = array();
array_map(function($item) use (&$result)
{
$types = explode("," , $item['types']);
if(count($types) == 1)
{
$result[$item['types']] = array(
$item['ids'] => explode("," , $item['values'])
);
}
else
{
foreach ($types as $type)
{
$result[$type] = array(
$item['ids'] => explode("," , $item['values'])
);
}
}
}, $matches);
var_dump($result);