在php中将字符串转换为多维数组

时间:2015-04-15 05:23:11

标签: php arrays types

我在php中将字符串转换为多维数组时遇到了问题。这是我的字符串:

$String = a,b,c|d,e,f|g,h,y|

这就是我正在尝试的:

$one=explode("|",$String);
foreach ($one as $item)
{
    $one=explode(",",$one);
}

我想创建这个数组:

$array={ {a,b,c}, {d,e,f}, {g,h,y} };

5 个答案:

答案 0 :(得分:3)

尝试 -

$one=explode("|",$String);
$array = array();
foreach ($one as $item){
    $array[] = explode(",",$item);
}

答案 1 :(得分:2)

试试这段代码:

$string = 'a,b,c|d,e,f|g,h,y|';
$arr = array_map(function($iter){ return explode(',',$iter);},explode('|',$string));

希望它有所帮助。

答案 2 :(得分:2)

除了循环部分之外,你几乎做得很好。试试这个

$result = [];
$String = 'a,b,c|d,e,f|g,h,y|';

$firstDimension = explode('|', $String); // Divide by | symbol
foreach($firstDimension as $temp) {
    // Take each result of division and explode it by , symbol and save to result
    $result[] = explode(',', $temp);
}

print_r($result);

答案 3 :(得分:1)

试试这个 -

$String = 'a,b,c|d,e,f|g,h,y|';

$one = array_filter(explode("|", $String));

print_r($one); //Array ( [0] => a,b,c [1] => d,e,f [2] => g,h,y ) 

$result = array_map('v', $one);

function v($one) {
    return explode(',',$one);
}

print_r($result); // Array ( [0] => Array ( [0] => a [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ) [2] => Array ( [0] => g [1] => h [2] => y ) )

答案 4 :(得分:0)

使用此代码

$String= 'a,b,c|d,e,f|g,h,y|';

$one=explode("|",$String);

print_r(array_filter($one));

输出

Array
(
    [0] => a,b,c
    [1] => d,e,f
    [2] => g,h,y
)