Tedxxxx
Tedxxxx

Reputation: 258

Convert a one dimensional array to two dimensional array

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.

Upvotes: -4

Views: 2634

Answers (4)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: -1

Nawin
Nawin

Reputation: 1692

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

Upvotes: -1

kinggs
kinggs

Reputation: 1168

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

Upvotes: 1

Keyur Padalia
Keyur Padalia

Reputation: 2097

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

Upvotes: -1

Related Questions