[英]Filtering an array result in a for each loop
I have this code to create my array from file: 我有以下代码可以从文件创建数组:
<?php
$servers = array();
$handle = @fopen("data/data.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$line = explode("|", $buffer);
$servers[] = array(
"name" => $line[0],
"ip" => $line[1],
"type" => $line[2],
);
}
fclose($handle);
}
?>
then i have this code to display the array: 然后我有这段代码来显示数组:
<?php
foreach ($servers as $name => $servers): ?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php endforeach; ?>
this is the array sample: 这是数组示例:
Array(
[0] => Array
(
[name] => aaa
[ip] => 123
[type] => good
)
[1] => Array
(
[name] => bbb
[ip] => 345
[type] => good
)
)
suppose i need to filter the result with array type is good, im trying with this code but it only returns the last array: 假设我需要用数组类型过滤结果是好的,我尝试使用此代码,但它仅返回最后一个数组:
<?php
foreach ($servers as $name => $servers): ?>
<?php if($servers['type']=="good"){?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
The error is in the variable name in foreach loop (use $server instead of $serves as $servers already exists and contains your data) 错误出在foreach循环中的变量名中(使用$ server代替$ serves,因为$ servers已经存在并包含您的数据)
<?php foreach ($servers a $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
Filter the array, then print it 过滤数组,然后打印
<?php
//Filter the array
$goodValues = array_filter($servers, function($e){
return $e['type'] == "good";
//Use this to be sure
//return strtolower($e['type']) == "good";
});
//Print the values
foreach ($goodValues as $value): ?>
<tr>
<td style="width:340px;"> <?php echo $value['name']; ?></td>
<td style="width:240px;"><?php echo $value['ip']; ?></td>
</tr>
<?php endforeach; ?>
As this is just numaric array and you're not using the key anywhere inside the body of the loop, you don't need to use as $key => $value
and only as $value
will suffice. 由于这只是numaric数组,并且您不在循环主体内的任何地方使用键,因此您无需将其
as $key => $value
而只需as $value
就足够了。 Also notice the different variable names. 还要注意不同的变量名。
<?php foreach ($servers as $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.