【问题标题】:how do i replace a character in my array with another character? [duplicate]如何用另一个字符替换数组中的字符? [复制]
【发布时间】:2016-04-08 05:22:11
【问题描述】:

我有一个数组 - 我的数组的输出如下所示:

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["-"] => 7
    ["FR"] => 3
)

我想用“其他”替换“-”

所以最后应该是这样的:

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["other"] => 7
    ["FR"] => 3
)

有人可以帮我解决这个问题吗? str_replace 没有和我一起工作...... 如果可以的话,我想将数组的“其他”部分放在底部- 像这样:

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["FR"] => 3
    ["other"] => 7
)

谢谢:)

当前代码:

 $array_land = explode("\n", $land_exec_result);
 $count_land = array_count_values($array_land);
        arsort($count_land);
        $arr['other'] = $count_land["-"];
        unset($count_land["-"]);

但这对我没有用:/

【问题讨论】:

  • 该死的..现在需要下线..但我会回复任何试图帮助我的人:)

标签: php arrays


【解决方案1】:
$arr['other'] = $arr['-'];
unset($arr['-']);

第一个命令将$arr['-'] 元素的值存储在名为$arr['other'] 的新元素中。当您以这种方式为具有命名索引的数组创建新元素时,新元素将自动放置在数组的末尾。

第二个命令从数组中删除$arr['-'] 元素。 结果将是:

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["FR"] => 3
    ["other"] => 7
)

【讨论】:

  • 你需要解释你的答案。 SO 的存在不仅仅是为了回答问题,而是教人们如何编码。
  • 你好,对不起,我没有早点回复......谢谢你的回答,但它对我没有用:o我更新了我的问题,所以我们可以争取一个解决方案:)
  • php 刚刚给了我一个:未定义的索引:-(所以 php 找不到“-”字符)
【解决方案2】:

就这么简单:

$array["other"] = $array["-"];
unset($array["-"]);

最后,数组会是这样的:

Array
(
    ["US"] => 186
    ["DE"] => 44
    ["BR"] => 15
    ["FR"] => 3
    ["other"] => 7
)

【讨论】:

  • 我编辑了我的问题 :) 这在你的回答中对我没有用:/
  • php 只是给了我一个:未定义的索引:-(所以 php 找不到“-”字符)
  • 你确定数组 $count_land 有“-”索引吗?如果你 print_r $count_land 会输出什么?
  • 你在我的问题中看到的是 $count_land 的输出 :)
  • 是的我知道了
猜你喜欢
  • 1970-01-01
  • 2011-11-14
  • 2018-06-16
  • 1970-01-01
  • 2021-05-09
  • 2021-03-30
  • 2020-02-08
  • 2021-06-15
  • 1970-01-01
相关资源
最近更新 更多