【问题标题】:PHP - modify formatted arrayPHP - 修改格式化数组
【发布时间】:2019-11-07 14:02:19
【问题描述】:

我有一个用于插入到 db 中的数组的函数。

$data = array(
 "This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);

我正确地格式化它并且给定的输出是:

$result = array_walk($data, function(&$item) { $item = '{ ' .str_replace("\t", ', ', $item) . ' }'; });

并且以 JSON 格式插入到 db 中的其中一行的结果是:

{ This, is, Example }, {  One, Of, My, Arrays}

所有这些都是这样格式化的。

我怎样才能绕过它来获得所需的格式,例如:

{ This, is, Example, One, Of, My, Arrays}

【问题讨论】:

  • 这不是有效的 JSON 开头 - 花括号表示对象,因此您需要在其中包含键值对。
  • 我的格式正确,我不同意。为什么不在字符串上使用explode,然后简单的json_encode
  • 因为您的代码应该可以工作,如果您删除 $data 中的最后一个 \,为什么还要在 One 后面加上引号?在 php 中查看查询的执行会很有帮助
  • 当我运行给定的代码时,$data 是一个数组并且包含{ This, Is, An, Example, One, Of, My, Arrays } 作为第一个元素。因此,您的转储输出看起来不同,这看起来很奇怪——尤其是An 在当前和预期输出中都消失了

标签: php arrays array-walk


【解决方案1】:

如果你想转换这个

$data = array(
 "This\tIs\tAn\tExample\tOne\tOf\tMy\tArrays\"
);

到这里

{ This, is, Example, One, Of, My, Arrays}

你可以这样做

$result = [];
    foreach ($data as $index => $value) {
        $result[] = implode(',', explode("\t", $value));
    }
    $result = '{' . implode(',', $result) . '}';

【讨论】:

  • 它返回 ""{Id,FirstName,LastName,DateOfBirth,Phone,Address1,Address2,City,State,PostCode,Country,Email}"" 对 explode('\\', $value)) 爆炸("\t", $value)) @GeorgeDryser
  • 您还需要将其更改为使用双引号 "\t"
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 2012-06-03
  • 2011-09-01
  • 1970-01-01
相关资源
最近更新 更多