【问题标题】:Associative array replace关联数组替换
【发布时间】:2018-02-20 21:56:21
【问题描述】:

这些数组包含相同的键,就像关注主题一样简单(prop 是唯一的): Check if associative array contains value, and retrieve key / position in array

<?php
$array = array(
array("prop" => "1", "content" => "text"),
array("prop" => "2", "content" => "text"),
array("prop" => "3", "content" => "text"),
array("prop" => "4", "content" => "text")
);
$found = current(array_filter($array, function($item) {
  return isset($item['prop']) && 3 == $item['prop'];
}));
print_r($found);

我得到了prop 3:

Array
(
  [prop] => 3
  [content] => text
)

所以我想将$array 中的值替换为:

array("prop" => "3", "content" => "replaced text")

【问题讨论】:

  • 什么?你想要什么结果?
  • array("prop" => "3", "content" => "replaced text") in $array
  • prop 总是唯一的吗?
  • yes 总是独一无二的

标签: php arrays associative-array


【解决方案1】:

由于prop 是唯一的,只需使用prop 作为索引提取数组,然后以这种方式访问​​它:

$array = array_column($array, null, 'prop');
$array[3]['content'] = 'replaced text';

您可能希望使用isset 来确保$array[3]['content'] 存在。

【讨论】:

  • 从技术上讲,OP 不应该将值作为$array['3']['content'] 访问,因为“prop”是原始数组中的字符串?我相信通过整数访问它可能会导致数组位置和数组键名之间出现问题。
  • @Anthony:PHP 从仅包含整数的字符串创建整数键 var_dump(["1"=&gt;"hello", "a"=&gt;"hello"]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多