打印数组的键 [英] Print the keys of an array

查看:44
本文介绍了打印数组的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何将可变数量的变量传递给函数.我认为传入一个数组并使用数组键作为变量名称可以代替将额外变量传递给函数的需要,并且它起作用了(我确定有更好的方法来实现这一点,欢迎提出建议).但是,我似乎无法从函数内部的数组中取出键.

I could not figure out how to pass a variable number of variables into a function. I thought passing in an array and using the array keys for the variables names could replace the need to pass extra variables into the function, and it worked (I'm sure there is a better way to accomplish this, suggestions welcome). However, I can't seem to get the keys out of the array inside the function.

数组:

  $parameters[day] = 1;
  $parameters[month] = 8;
  $parameters[year] = 2010; 

函数内部:

foreach(key($parameters) as $key)
{
   print($key);
   print("<br>");
}

函数内的代码返回一个警告:为 foreach() 提供的参数无效.如何将键从数组中拉出?

The code inside the function retuns a warning: Invalid argument supplied for foreach(). How can I pull the keys out of the array?

推荐答案

你可以使用 PHP 的 array_keys 函数来获取键,就像这样:

You can use PHP's array_keys function to grab the keys, like so:

foreach(array_keys($parameters) as $paramName)
  echo $paramName . "<br>";

或者,您可以使用特殊的 foreach 遍历数组,它允许您将每个元素的键和值分开,如下所示:

Or, you can run through the array using a special foreach which allows you to separate the key and value for every element, like so:

foreach($parameters as $paramName => $value)
  echo $paramName . "<br>";

此外,请确保您使用 "string"(带引号)或整数(如 1337)作为键,如下所示:

Also, make sure that you are using a "string" (with quotes) or integer (like 1337) as your key, like so:

$parameters["day"] = 1;
$parameters["month"] = 8;
$parameters["year"] = 2010;

或者,如果你想变得更狂热:

OR if you want to get fancier:

$parameters = array(
  "day" => 1,
  "month" => 8,
  "year" => 2010
);

您的代码应如下所示:

$parameters = array(
  "day" => 1,
  "month" => 8,
  "year" => 2010
);
foreach($parameters as $paramName => $paramValue)
  echo $paramName . "<br>";

这篇关于打印数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆