简体   繁体   English

php数组将密钥从foreach循环存储到字符串中

[英]php Array storing key from a foreach loop into string

I have a key-pair array like this 我有这样的密钥对数组

$option['33']="Steak Doness";
$option['34']="Size";
$option['35']="Cooking Method";

I want to store the keys into a string like this 我想将密钥存储在这样的字符串中

$key="33,34,35,";

I try to use foreach loop 我尝试使用foreach循环

$key="";

foreach($option as $key => $value) {
    $key=$key.",";
}
echo $key;

However, my output is 但是,我的输出是

35,

May i know which part went wrong? 我可以知道哪一部分出了错吗?

You miss use the $key in your script. 您会错过在脚本中使用$key

The problem is with the $key which is in the foreach loop... . 问题出在foreach循环中的$key In each time your $key variable updated with the loop... Try with difference variable in your script. 每次$key变量使用循环更新时...在脚本中尝试使用different变量。

OR, simply use 或者,只需使用

echo $key = implode(",", array_keys($option));

1st change your varible $key to $keys replace one line 第一种将变量$ key更改为$ keys替换一行

$key=$key.",";

to

$keys .= $key . ",";

it will work 100% 它将100%工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM