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

时间:2017-09-11 08:21:32

标签: php arrays dimensional

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

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

但它不起作用。

5 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您可以这样做:

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

答案 2 :(得分:0)

$AR = array('id,"1"', 'name,"abcd"', 'age,"30"');
$val = array();
foreach ($AR as $aa){
  $val[] = array($aa);
}
print_r($val);
  

输出:

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

答案 3 :(得分:0)

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

$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

答案 4 :(得分:0)

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