从多维数组访问和爆炸以逗号分隔的数据,然后填充一个新的二维数组



我有一个多维数组,包含像这样的逗号分隔字符串

[
    [
        "users" =>  [
            'email' => 'test@yahoo.com ,testuser@yahoo.com',
            'username' => 'test,testuser',
            'description' => 'description1,description2'
        ]
    ]
]

我想访问users子数组数据,在分隔符上爆炸,并创建一个索引数组的新关联数组。

预期的结果:

$User = array(
    'email' => array(
        'test@yahoo.com',
        'testuser@yahoo.com'
    ),
    'username' => array(
        'test',
        'testuser'
    ),
    'description' => array(
        'description1',
        'description2'
    )
);

仅用于一个索引:

$arrayTwoD = array();
foreach ($valueMult[0]['User'] as $key => $value) { 
    $arrayTwoD[$key] = array_push(explode(',', $value));
}

如果在$multArray中有多个索引:

$arrayTwoD = array();
foreach ($multArray as $keyMult => $valueMult) { 
    foreach ($valueMult['User'] as $key => $value) { 
        $arrayTwoD[$keyMult][$key] = array_push(explode(',', $value));
    }
}

$arrayTwoD = array();
foreach ($multArray as $array) { 
    foreach ($array['User'] as $key => $value) { 
        $arrayTwoD[$key] = array_push(explode(',', $value));
    }
}

try this

$array = array(...); // your array data
$formedArray = array();
foreach ( $array as $arr )
{
    foreach ( $arr['user'] as $key => $value )
    {
        $formedArray[$key] = array_push(explode(",",$value));
    }
}
echo "<pre>";
print_r($formedArray);
echo "</pre>";

我知道这有点重复,但你也可以这样做:

foreach($array as $users) {
    foreach($users as &$value) { // &value is assigned by reference
        $users['users']["email"] = explode(",", $value['email']);
        $users['users']["username"] = explode(",", $value['username']);
        $users['users']["description"] = explode(",", $value['description']);
    }
}

但在那之后,你需要使用$value。参考PHP官方手册文档,了解更多关于&符号的作用。

演示

使用array_map()可以访问子集数据(不需要在全局范围内声明任何新变量),并对preg_split()进行迭代调用,以将分隔的值分隔成子数组。

代码(演示):

var_export(
    array_map(
        fn($csv) => preg_split('/ ?,/', $csv),
        $array[0]['users']
    )
);

相关内容

  • 没有找到相关文章

最新更新