0

我不是要你为我写代码。任何方向将不胜感激。

我有一个格式如下的数组:

Array
(
[0] => Array
  (
  [title] => Here is the first title
  [count] => 765
  [description] => Description
  )
[1] => Array
  (
  [title] => The second title
  [count] => 90
  [description] => Description
  [other] => Data
  )
[2] => Array
  (
  [title] => A third title
  [count] => 1080
  [description] => Description
  )
)

我想知道如何使用“标题”和“计数”数据将其转换为如下所示的内容。

Array
(
[Here is the first title] => 765
[The second title] => 90
[A third title] => 1080
)

目前我已经创建了以下代码:

$results = array();
foreach ($inputarray as $value) {
    $results[] = $value["count"];
}

这给了我以下内容:

Array
(
[0] => 765
[1] => 90
[2] => 1080
)

但我不确定如何使标题数据成为其关联计数数据的新键。有没有可以做到这一点的功能?可以对上述进行修改还是更复杂?谢谢你的帮助。

4

2 回答 2

0

只需使用标题显式填充新数组的键:

$results = array();
foreach ($inputarray as $value) {
    $results[$value["title"]] = $value["count"];
}

请注意,任何具有相同标题的条目都会覆盖前一个条目,因为数组键必须是唯一的。我怀疑这是实现您的目标的最佳方式,但这是您所要求的。

于 2013-07-07T03:40:38.223 回答
0

一种方法是使用 array_reduce 和闭包(需要 PHP 5.3+)

$res = array_reduce($array, function (&$results, $v){
     $results[$v["title"]] = $v["count"];
}, array());
于 2013-07-07T04:03:04.117 回答