将字符串转换为预定义的2D数组

时间:2012-01-09 23:29:37

标签: php

  

可能重复:
  convert string to 2D array using php

我有如下字符串:

01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16

如何将上面的字符串转换为如下所示的定义数组:

$a[0] = array('column' => array("row1" => "01", "row2"=> "05", "row3" => "07", "row4" =>"12"));
$a[1] = array('column' => array("row1" => "03", "row2"=> "04", "row3" => "09", "row4" =>"14"));
$a[2] = array('column' => array("row1" => "02", "row2"=> "06", "row3" => "08", "row4" =>"13"));
$a[3] = array('column' => array("row1" => "15", "row2"=> "10", "row3" => "11", "row4" =>"16"));

我知道我应该使用爆炸功能,但不确定应该如何实现这一点,任何帮助都将非常感谢,谢谢!

3 个答案:

答案 0 :(得分:4)

使用这种格式你基本上只需要:

$a = array_map("str_getcsv", explode("|", $string));

它为您提供了一个枚举数组。如果您需要特定的命名密钥,那么您必须再次对此结构进行后处理:

foreach ($a as $i=>$row) {
    $a[$i] = array("column" => array("row1"=>$row[0], "row2"=>$row[1], "row3"=>$row[2], "row4"=>$row[3]));
}

答案 1 :(得分:1)

我认为这就是你要找的东西:

<?php

$a = array();
$str = "01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16";

$arr = explode("|", $str);
for ($i = 0; $i < count($arr); $i++) {

    $a[$i] = array('column' => array());

}

for ($i=0; $i<count($arr); $i++) {

    $arr2 = explode(",", $arr[$i]);

    for ($j = 0; $j < count($arr2); $j++) {

        $key = "row" . intval($i + 1);
        $a[$j]['column'][$key] = $arr2[$j];

    }

}

echo "<pre>";
var_dump($a);

?>

答案 2 :(得分:0)

$sequence = "01,03,02,15|05,04,06,10|07,09,08,11|12,14,13,16";
$columns = explode("|", $sequence);

$result = array();

foreach ($columns as $i => $column)
{
    $rows = explode(",", $column);
    $sub_array = array();
    foreach ($rows as $id => $row)
    {
        $sub_array["row".($id+1)] = $row;
    }
    $result[$i] = array('column' => $sub_array);
}