如何将多维数组展平为字符串?

时间:2017-08-24 13:44:57

标签: php arrays multidimensional-array

我已经研究了这个,但即将发布空白,我从数据库生成一系列测试:

$descriptions = array();
foreach ($tests as $value) {
    array_push($descriptions, ['name' => $value['name']]);
}

我得到了理想的输出,但我得到的数组的多维数组中包含'[64]'数组' $描述',我需要转换此数组所以我得到以下输出: 所有结果'name' => $value1, 'name' => $value2, etc etc, 我已经尝试过implode,array_merge等,但我最接近的是一个只有我最后一次测试的平面阵列:[name] => Zika任何人都能指出我正确的方向吗?欢呼声

1 个答案:

答案 0 :(得分:1)

您不能拥有重复的数组键。但你可以像这样传递一个数组:

<?php

$descriptions = array();
$tests = array(
    'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',    
);

foreach ($tests as $value) {
    $descriptions[] = array('name' => $value);
}

var_dump($descriptions);

这给了你:

array(6) { [0]=> array(1) { ["name"]=> string(4) "Zika" } [1]=> array(1) { ["name"]=> string(4) "SARS" } [2]=> array(1) { ["name"]=> string(4) "AIDS" } [3]=> array(1) { ["name"]=> string(15) "Mad Cow Disease" } [4]=> array(1) { ["name"]=> string(8) "Bird Flu" } [5]=> array(1) { ["name"]=> string(16) "Zombie Infection" } }

所以你可以foreach ($descriptions as $desc)echo $desc['name']';

看看这里:https://3v4l.org/pWSC6

如果你只想要一个字符串,试试这个:

<?php

$descriptions = '';
$tests = array(
    'Zika', 'SARS', 'AIDS', 'Mad Cow Disease', 'Bird Flu', 'Zombie Infection',    
);

foreach ($tests as $value) {
    $descriptions .= 'name => '.$value.', ';
}
$descriptions = substr($descriptions, 0, -2); // lose the last comma
echo $descriptions;

将输出:

name => Zika, name => SARS, name => AIDS, name => Mad Cow Disease, name => Bird Flu, name => Zombie Infection

在此处查看https://3v4l.org/OFGF4