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

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

问题描述

我无法弄清楚如何通过可变数量的变量转换函数。我想传递一个数组,并使用该变量的名称数组键可以替代需要额外的变量传递到函数,它的工作(我敢肯定有一个更好的方式来做到这一点,建议表示欢迎)。不过,我似乎无法拿到钥匙了函数中的数组。

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>");
}

该函数中的code retuns警告:提供的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>";

此外,请确保您使用的是(带引号)或整数(如 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
);

您code应该是这样的:

Your code should look like:

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

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

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