在数组中插入一个数组?

时间:2017-10-21 07:09:46

标签: php arrays implode

我想在我的数组中加载所有字符,但是当我加载输出时只有

0K11LS19T20B2C32M13NU21V1

我是否需要为其他角色创建另一个数组,或者我的代码中有错误?

<?php

$alphNm = array
(
array("tag" => "A1B2C","tag" => "3D4E5","tag" => "F6G7H","tag" => "8I9J1","tag" => "0K11L"),
array("tag" => "12M13","tag" => "N14O1","tag" => "5P16Q","tag" => "17R18","tag" => "S19T2"),
array("tag" => "0U21V","tag" => "22W23","tag" => "X24Y2","tag" => "5Z26A","tag" => "0B2C3"),
array("tag" => "D4E5F","tag" => "6G7H8","tag" => "I9J10","tag" => "K11L1","tag" => "2M13N"),
array("tag" => "14O15","tag" => "P16Q1","tag" => "7R18S","tag" => "19T20","tag" => "U21V1")

);
echo implode(', ', array_map(function ($entry) {
        return $entry['tag'];
      }, $alphNm));
      
?>

2 个答案:

答案 0 :(得分:0)

尝试这种方法

docs

结果如下

A1B2C3D4E5F6G7H8I9J10K11L12M13N14O15P16Q17R18S19T20U21V22W23X24Y25Z26A0B2C3D4E5F6G7H8I9J10K11L12M13N14O15P16Q17R18S19T20U21V1

答案 1 :(得分:0)

数组中有一个数组。要使用implode,您需要一个数组。看起来你用array_map尝试了这个,但这不是正确的方法,因为你内部数组中的键都是相同的。

这就是你的问题:PHP会将array("tag" => "A1B2C","tag" => "3D4E5","tag" => "F6G7H","tag" => "8I9J1","tag" => "0K11L")解释为具有唯一条目tag => "0K11L"的数组,因为这是最后一个条目。例如使用var_dump;)

你需要这个“标签”吗?你需要数组中的数组吗?如果两者都没有,你可以简单地将输入简化为这样的一个数组:

$alphNm = array("A1B2C", "3D4E5", "F6G7H", "8I9J1", "0K11L", "12M13", <...>);
echo implode(", ", $alphNm):

一个阵列中的所有内容。然后implode(", ", $alphNm)就可以了。如果在一个数组中仍然需要这4个数组,则可以迭代第一个外部数组以获取内部数组的内容并将其添加到数组中。如果你删除这个不必要的“标签”,那么你也可以做这个小技巧:

$alphNm = array(
    array("A1B2C","3D4E5","F6G7H","8I9J1","0K11L"),
    array("12M13","N14O1","5P16Q","17R18","S19T2")
);
echo implode(", ", array_merge(...$alphNm)));

...$alphNm将扩展您的外部数组(就像迭代它时一样)并且array_merge将其输入放在一个数组中。将字符串作为数组键时要小心这个函数,再次覆盖。