更新具有相同索引的PHP数组的所有值

时间:2015-02-06 06:51:00

标签: php arrays

这是我的数组结构:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [topic_id] => 
                    [user_id] => ZGNjBQN9ac3K
                    [owner_id] => 15157
                    [tagged_field] => description
                    [created_date] => 2015-02-06 12:11:54
                )

            [1] => Array
                (
                    [topic_id] => 
                    [user_id] => ZGNjAmD9ac3K
                    [owner_id] => 15157
                    [tagged_field] => description
                    [created_date] => 2015-02-06 12:11:54
                )

        )

)

我在保存主题之前生成了这个结构,因此我将在此之后获得主题ID。

因此,为了保存这个数组,我需要将主题id设置为所有索引&#34; topic_id&#34; ...假设如果topic_id是11234,我需要使用值为11234的topic_id更新所有索引。< / p>

期望的输出:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [topic_id] => 11234
                    [user_id] => ZGNjBQN9ac3K
                    [owner_id] => 15157
                    [tagged_field] => description
                    [created_date] => 2015-02-06 12:11:54
                )

            [1] => Array
                (
                    [topic_id] => 11234
                    [user_id] => ZGNjAmD9ac3K
                    [owner_id] => 15157
                    [tagged_field] => description
                    [created_date] => 2015-02-06 12:11:54
                )

        )

)

3 个答案:

答案 0 :(得分:1)

尝试 -

$indexedArray = array();
foreach($yourArray as $value) {
   foreach($value as $val) {
      $indexedArray[$val['topic_id']][] = $val;
   }
}

答案 1 :(得分:0)

您可以使用 reference 变量(例如

)以简单方式完成
$yourArray = array(array(array("topic_id"=>"","user_id"=>110),array("topic_id"=>"","user_id"=>786)));

foreach($yourArray as &$value) {
   foreach($value as &$val) {
      $val['topic_id'] = "your_topic_id";
   }
}

<强>输出

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [topic_id] => your_topic_id
                    [user_id] => 110
                )

            [1] => Array
                (
                    [topic_id] => your_topic_id
                    [user_id] => 786
                )

        )

)

答案 2 :(得分:0)

您需要在foreach循环中使用引用:

$arr = array(
    array(
      array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
      array("topic_id" => "", "user_id" => "ZGNjBQN9ac3K", "owner_id" => "15157", "tagged_field" => "description", "created_date" => "2015-02-06 12:11:54"),
    )
);

foreach($arr as &$value) {
   foreach($value as &$val) {
      $val['topic_id'] = $newvalue;
   }
}
print_r($arr);