0

Possible Duplicate:
convert string to 2D array using php

I have the string like the following:

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

how can I convert the above string to a defined array like the one below:

$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"));

I know I should use explode function but not sure how exactly it should be implemented for this, any help would be greatly appreciated, thanks!

1
  • In the future, just update your existing question. Commented Jan 10, 2012 at 14:09

3 Answers 3

4

With that format you basically just need:

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

That gives you an enumerated array. If you want your specific named keys, then you have'd to post-process this structure again:

foreach ($a as $i=>$row) {
    $a[$i] = array("column" => array("row1"=>$row[0], "row2"=>$row[1], "row3"=>$row[2], "row4"=>$row[3]));
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think this is what you are looking for:

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

?>

Comments

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);
}

1 Comment

the = array(); initializations aren't needed, but I keep writing them down :) actually in the second case you somehow need to reset the variable like ($sub_array = array();), because it's scope doesn't end after one loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.