将一维数组转换为二维数组

Convert a one dimensional array to two dimensional array

我有一个数组,它的结构基本上是这样的:

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

我想将其转换为二维数组,其中每个元素作为键 -> 值:

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

如有任何建议,我们将不胜感激!

我试过这段代码:

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

但是没用。

你可以这样做:

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

您希望这些字符串作为数组中的数组吗?如果是,这里是解决方案:

$array = array('id,"1"', 'name,"abcd"', 'age,"30"') //it's array of 3 strings
$d_array = array(); //it's an empty array

//foreach string of first array
foreach ($array as $a) {
   $pieces = explode(',',$a); //from string to array
   $d_array[] = $pieces; //insert array to the array
}

var_dump($d_array); //your new multi array

假设您想根据您的问题删除所有引号:

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

具有array_map功能:

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

print_r($result);

输出:

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

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

    [2] => Array
        (
            [age] => "30"
        )
)