Convert a one dimensional array to two dimensional array

2.5k views Asked by At

I have an array, whose structure is basically like this:

array('id,"1"', 'name,"abcd"', 'age,"30"')

I want to convert it into a two dimensional array, which has each element as key -> value:

array(array(id,1),array(name,abcd),array(age,30))

Any advice would be appreciated!

I tried this code:

foreach ($datatest as $lines => $value){
    $tok = explode(',',$value); 
    $arrayoutput[$tok[0]][$tok[1]] = $value;
}

but it didn't work.

4

There are 4 answers

0
kinggs On BEST ANSWER

Assuming you want to remove all quotation marks as per your question:

$oldArray = array('id,"1"', 'name,"abcd"', 'age,"30"')
$newArray = array();
foreach ($oldArray as $value) {
  $value = str_replace(array('"',"'"), '', $value);
  $parts = explode(',', $value);
  $newArray[] = $parts;
}
0
RomanPerekhrest On

With array_map function:

$arr = ['id,"1"', 'name,"abcd"', 'age,"30"'];
$result = array_map(function($v){
    list($k,$v) = explode(',', $v);
    return [$k => $v];
}, $arr);

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [id] => "1"
        )

    [1] => Array
        (
            [name] => "abcd"
        )

    [2] => Array
        (
            [age] => "30"
        )
)
0
Keyur Padalia On

You can do something like this:

$a = array('id,"1"', 'name,"abcd"', 'age,"30"');
$b = array();
foreach($a as $first_array)
{
    $temp = explode("," $first_array);
    $b[$temp[0]] = $b[$temp[1]];
}
0
Nawin On
$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
  $val[] = array($aa);
}
print_r($val);

Output:

Array ( [0] => Array ( [0] => id,"1" ) [1] => Array ( [0] => name,"abcd" ) [2] => Array ( [0] => age,"30" ) )