【问题标题】:PHP - How to add two arrays with a string in betweenPHP - 如何在两个数组之间添加一个字符串
【发布时间】:2017-09-14 21:22:07
【问题描述】:

我有两个数组。我想在它们之间添加: 并将它们都添加到另一个数组中。

$temp = json_decode($csv[$indexLoc['allowance_json']], TRUE);

$details = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';
$anytime = is_array($temp)?(array_key_exists('anytime', $temp)?$temp['anytime']:''):'';

$deals[$counter]['deal_mins'] = $details .":". $anytime;

我需要上面的代码才能工作。
我也有基本的,总是有效的

$deals[$counter]['deal_mins'] = is_array($temp)?(array_key_exists('details', $temp)?$temp['details']:''):'';

这个可行,但我需要用: 分隔两个数组。

【问题讨论】:

  • 错误?究竟是什么行不通?看起来不错。
  • 数组不能用:分隔。
  • 你能尝试创建一个minimal reproducible example吗?这里有一些代码,很好,但我们确实需要至少查看一个输入示例、一个您尝试获得的输出示例以及一个您正在获得的示例。
  • 他是否想根据这些值创建一个新的 JSON 对象?
  • 好吧,我换个方式再解释一遍。

标签: php arrays json variables


【解决方案1】:

您是否遇到任何错误?您的代码看起来不错。

$allowance_json = '{"details":"foo", "anytime":"bar"}';

$temp = json_decode($allowance_json, TRUE);

if (is_null($temp)) throw new Exception(json_last_error());

$details = (isset($temp['details']) ? $temp['details'] : '');
$anytime = (isset($temp['anytime']) ? $temp['anytime'] : '');              

echo $details . ':' . $anytime;

那个输出是一个字符串。您从那里提取的字符串值由: 连接。使用下面的代码行,您将该字符串推回数组中。这就是你想要的吗?

$deals[$counter]['deal_mins'] = $details . ":" . $anytime;

【讨论】:

  • 它只是给了我数据库中的“数组:”。
  • 嗯,我不知道你在这里和数据库之间做什么。如果你var_dump($deals[$counter]['deal_mins']) 你不会得到任何关于 array 的信息。你会得到一串文本。假设在您的示例中 $details$anytime 是字符串。你应该检查一下。我不能说因为你从来没有展示过$csv[$indexLoc['allowance_json']]的内容
  • 非常感谢,因为有你,我明白了一切并能够解决问题。
猜你喜欢
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
相关资源
最近更新 更多