PHP获取键值

PHP获取键值,php,arrays,Php,Arrays,我试图从数组中获取密钥,以使div成为: <div id="item"> <div id="item-1"> <div id="item-2"> <div id="item-3"> 固定代码: $a = $something['no']; $array = array_fill(0, $a, 'value'); foreach($array as $key => $value){ if($key == '0') { $x = 'ite

我试图从数组中获取密钥,以使div成为:

<div id="item">
<div id="item-1">
<div id="item-2">
<div id="item-3">
固定代码:

$a = $something['no'];
$array = array_fill(0, $a, 'value');
foreach($array as $key => $value){
 if($key == '0') {
  $x = 'item';
 } else {
  $x = 'item-'.$key;
 }
 $insert .= '<div id="'.$insert = $x.'">';
  // content here
 $insert .= '</div>';
}
$a=$something['no'];
$array=array_fill(0,$a,'value');
foreach($key=>$value的数组){
如果($key==“0”){
$x='项目';
}否则{
$x='item-'。$key;
}
$insert.='';
//满足于此
$insert.='';
}

您可以使用
for
循环最小化代码:

$something['no'] = 4;

$html = '';
for ($i = 0; $i < $something['no']; $i++) {
  $x = !$i ? '' : "-{$i}";
  $content = "woof woof";
  $html .= "<div id=\"item{$x}\">".$content."</div>\n";
}
print_r($html);
$something['no']=4;
$html='';
对于($i=0;$i<$something['no'];$i++){
$x=!$i?'':“-{$i}”;
$content=“woof-woof”;
$html.=''.$content.\n“;
}
打印(html);

节省了分配变量和运行单独的进程来用数字填充数组的时间,您只需将这些数字相加即可

让我们
打印\u r
您的
$array
没有打印任何内容,我还尝试了var\u dumpLook。数组_fill函数的第二个参数应为整数。是吗?是的,因为foreach正在吐出正确数量的div,但是没有结尾$keyoops刚刚意识到它正在打印,内容在主帖子中(它被我主题中的某个东西隐藏了)。
$a = $something['no'];
$array = array_fill(0, $a, 'value');
foreach($array as $key => $value){
 if($key == '0') {
  $x = 'item';
 } else {
  $x = 'item-'.$key;
 }
 $insert .= '<div id="'.$insert = $x.'">';
  // content here
 $insert .= '</div>';
}
$something['no'] = 4;

$html = '';
for ($i = 0; $i < $something['no']; $i++) {
  $x = !$i ? '' : "-{$i}";
  $content = "woof woof";
  $html .= "<div id=\"item{$x}\">".$content."</div>\n";
}
print_r($html);