【问题标题】:How to convert string to an associative array in php [duplicate]如何在php中将字符串转换为关联数组[重复]
【发布时间】:2023-04-04 15:19:02
【问题描述】:

我有以下字符串。我需要将其转换为关联数组。结果,我得到的字符串来自 ajax,对于这种格式的字符串,我没有找到任何解决方案。

$string= '[{"name":"title","value":"%post_title%"},{"name":"author","value":"%author_name%"}]';

我需要将上面的字符串转换为关联数组,这样我就可以在 foreach 中使用该数组。

【问题讨论】:

  • 这是一个 JSON 字符串,所以使用 $array = json_decode($string,1); The manual
  • 我没有找到任何针对这种字符串格式的解决方案。我发现了同样的问题,但是那里的字符串格式不同。 @RiggsFolly
  • 查看json.org site 以熟悉 JSON 的外观。它现在用于很多事情

标签: php


【解决方案1】:

使用 json_decode 并将第二个参数设置为 true,以便将输入的 JSON 格式字符串转换为关联数组。

$string= '[{"name":"title","value":"%post_title%"},{"name":"author","value":"%author_name%"}]';

// convert the JSON format to array
$output_array = json_decode($string, true);

// print to check output
echo "<pre>"; print_r($output_array); echo "</pre>";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2021-11-23
    • 1970-01-01
    • 2012-08-07
    相关资源
    最近更新 更多