如何更改数组';s值使用PHP';它自己的功能


How to change an array's value using PHP's own functions

我有一个这样的数组:

$result = array(
    0 => array(
      "title" => "I am a hero!",
      "cat" => "literature",
      "date" => "23/7/2014",
   ),
   1 => array(
      "title" => "Significant Moment!",
      "cat" => "psychology",
      "date" => "29/7/2014",
   ),
   2 => array(
      "title" => "Coins do not count",
      "cat" => "economy",
      "date" => "23/7/2014",
   ),
);

现在我想递归地循环遍历数组,并检查当前键是否为"title",则请更改其值。类似这样的东西:

for(looping $result)
{
  if($current_key == "title")
  {
     $result[$current_key] = "Now title is change";
  }
}

我想使用PHP的数组函数来实现这一点。我认为array_walk_recursive是这个的选择。我尝试了以下代码,但它会更改每个值,而不仅仅是相应的密钥:

array_walk_recursive($results, function(&$item, $key) use(&$results){
                if($key == "title");
                {
                    $item = "Title Changed";
                }
            });

您的代码很好,但在if语句行的和处有分号,因此"if"被忽略

        array_walk_recursive($results, function(&$item, $key) use(&$results){
            printer($key, true, false, false);
            if($key == "title") {
                $item = "Title Changed";
            }
        });

没有理由递归遍历这个数组,因为您已经知道它的深度。

我的建议是使用一个简单的for循环:

for($i = 0; $i < sizeof($result); $i++)
    $result[$i]['title'] = "Now title is change";

如果你真的坚持使用array_函数,你可以像这样使用PHP的array_walk()

array_walk($result, function(&$a, $key){
    $a['title'] = "Now title is change";
});

工作示例

如果我没有错过什么,对我来说,你想要实现的似乎是一个简单的映射。。。

所以你可以使用array_map函数:

<?php
// $result = ...
$new_result = array_map(
    function($item){
        $item["title"] = "Now title is change";
        return $item;
    },
    $result
);
// Now $new_result is what you want.