【问题标题】:How to get only keys and values from php array?如何从 php 数组中只获取键和值?
【发布时间】:2020-10-05 19:13:40
【问题描述】:

我的 PHP 数组有一个问题,我似乎找不到解决方案。

我使用 str_replace 搜索键数组,并将其替换为另一个数组中的值

例子:

$findkeys = array("Key1","Key2","Key3");
$newvalues = array("Value 1","Value 2","Value 3");
$NewVal = str_replace($findkeys, $$newvalues,  "Hello, here is Key1 used");

这将 $NewVal 的值设置为“你好,这里使用的值 1”。

这就是我想要的

$Data = array("Key1"=>"Value1","Key2"=>"Value2","Key3"=>"Value3");
findkeys = ##Code to get all Keys into an array## Here!!
newvalues = ##Code to get all values into an array## Here!!
$NewVal = str_replace($findkeys, $$newvalues,  "Hello, here is Key1 used");

可以/如何做到这一点?

【问题讨论】:

  • 除了对键进行 if 检查的简单 foreach 之外,您还不清楚您想要什么。
  • 你真的写$$newvalues吗?
  • 我认为strtr() 是您想要的功能。它将采用关联数组并将所有键替换为其值。
  • array_keys()可以获取所有key,array_values()可以获取所有value。

标签: php arrays str-replace


【解决方案1】:

您需要使用array_keys()array_values()

$Data = array("Key1"=>"Value1","Key2"=>"Value2","Key3"=>"Value3");
$NewVal = str_replace(array_keys($Data), array_values($Data),  "Hello, here is Key1 used");

array_keys() 将返回数组的所有键,其中包含数字和顺序键作为数组。

array_values() 将返回具有数字和顺序键的数组的所有值作为数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2014-06-23
    • 2015-03-04
    相关资源
    最近更新 更多