phparraysdimensional

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.


Solution

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