我有这样的字符串:
$string = Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike
我做了什么:
$explode = ("; ", $string);
然后会显示它,如:
Array ([0] => Leader,Brian [1] => Elder,Nina,Maria [2] => Member,Duke,Rai,Mike)
但我不想那样。我想让它成为带有键和值的数组mutlidimentional,如下所示:
Array ([Leader] => Brian [Elder] => Array ([0] => Nina [1] => Maria)
[Member] => Array ([0] => Duke [1] => Rai [2] => Mike))
那么,如何在表格标签html中显示它呢?
Leader | Brian
Elder | Nina
| Maria
Member | Duke
| Rai
| Mike
感谢您的关注 NB:如果使用
这样的分隔符很困难,可以更改字符串中的分隔符答案 0 :(得分:3)
你explode
是迈出良好的第一步。
下一步是迭代其结果并再次爆炸。
然后(在同一循环中)使用第二个explode
结果的第一个元素作为键,其余部分作为值。
$string = "Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike";
$exploded = explode("; ", $string);
foreach($exploded as $element) {
$arr = explode(',', $element);
$result[array_shift($arr)] = $arr;
}
var_dump($result);
结果:
array(3) {
["Leader"]=>
array(1) {
[0]=>
string(5) "Brian"
}
["Elder"]=>
array(2) {
[0]=>
string(4) "Nina"
[1]=>
string(5) "Maria"
}
["Member"]=>
array(3) {
[0]=>
string(4) "Duke"
[1]=>
string(3) "Rai"
[2]=>
string(4) "Mike"
}
}
答案 1 :(得分:1)
我可能会在拆分字符串并再次拆分后走数组:
$list = explode("; ", $string);
array_walk($list, function(&$element) {
$names = explode(',', $element);
// Take the first item off the array type
$type = array_shift($names);
// Alter the array in-place to create the sub-array
$element = [$type => $names]
});
答案 2 :(得分:0)
你需要两个"爆炸"
$string = 'Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike';
$explode = explode("; ", $string);
foreach($explode as $row){
$explode2 = explode(",", $row);
foreach($explode2 as $i=>$p ){
echo ( $i > 0 )?"\n\t|":"\n";
echo $p;
}
}
答案 3 :(得分:0)
你需要在你的两个分隔符上爆炸两次,例如:
<?php
$string = "Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike";
$result = array();
$parts = explode(";", $string);
foreach ($parts as $part)
{
$kv = explode(",", $part);
$result[array_shift($kv)] = $kv;
}
// result:
echo '<pre>';
print_r($result);
echo '</pre>';
?>
会给你:
Array
(
[Leader] => Brian
[Elder] => Nina
[Member] => Duke
)
答案 4 :(得分:0)
这应该这样做:
<?php
$string = 'Leader,Brian; Elder,Nina,Maria; Member,Duke,Rai,Mike';
$explode = array_map(function($v){return explode(',', $v);}, explode(';', $string));
$new_array = [];
foreach($explode as $k=>$v)
{
$v[0] = trim($v[0]);
$new_array[$v[0]] = $v;
unset($new_array[$v[0]][0]);
$new_array[$v[0]] = array_values($new_array[$v[0]]);
}
print_r($new_array);