将数组键值对与分隔符关联

时间:2016-08-05 09:42:38

标签: php arrays pdo

$user  = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($user);

我得到的输出是:

Array
(
    [0] => Array
        (
            [ID] => US101
            [FirstName] => Ramesh
            [MobileNo] => 3125627127
            [City] => Bombay
        )

    [1] => Array
        (
            [ID] => US102
            [FirstName] => Ravindar
            [MobileNo] => 45624152627
            [City] => Culcatta
        )
)

我需要的输出是:

Array
(
    [US101] => US101 | Ramesh | 3125627127 | Bombay
    [US102] => US102 | Ravindar | 45624152627 | Culcatta
)

3 个答案:

答案 0 :(得分:2)

试试这个:

$formatted = [];
foreach($user as $v)
{
  $formatted[$v['ID']] = implode(' | ', $v);
}

print_r($formatted);

答案 1 :(得分:0)

您应该使用CONCAT_WS,如下所示

select CONCAT_WS('|',ID,FirstName,MobileNo,City) from table_name;

然后输出将是concat列值

答案 2 :(得分:0)

$userModified = array_map(function($item) {
    return [
        $item['id'] => implode($item, '|')
    ];
}, $user);