$outp = "[";
for($x = 1; $x <= 5; $x++) {
if ($outp != "[") {
$outp .= ",";
}
if ($ARRAY[$x]['name'] == "davies") {
$outp .= '{"name":"' . $ARRAY[$x]["name"] . '",';
$outp .= '"server_name":"' . $ARRAY[$x]["server"] . '",';
$outp .= '"uptime":"' . $ARRAY[$x]["uptime"] . '",';
$outp .= '"bytes_in":"' . $ARRAY[$x]["bytes-in"] . '",';
$outp .= '"bytes_out":"' . $ARRAY[$x]["bytes-out"] . '"}';
}
}
$outp .="]";
echo ($outp);
您好我试图从阵列中提取特定值,但我不知道该怎么做。所以我尝试将for循环函数与if语句一起使用。我想要做的就是搜索价值&#34; davies&#34;在数组[name]
中,然后从那里根据array[name]=davies
值拉出剩余的值。
我的阵列示例:
Array
(
[0] => Array
(
[.id] => *2
[server] => hotspot1
[name] => davies
[profile] => davies
[uptime] => 1d6m42s
[bytes-in] => 62669946
[bytes-out] => 459466004
)
[1] => Array
(
[.id] => *3
[server] => hotspot1
[name] => eric
[uptime] => 2h14m13s
[bytes-in] => 6836983
[bytes-out] => 15648003
)
[2] => Array
(
[.id] => *4
[server] => hotspot1
[name] => teck
[uptime] => 1h46m25s
[bytes-in] => 11847933
[bytes-out] => 166875279
)
[3] => Array
(
[.id] => *5
[server] => hotspot1
[name] => andy
[uptime] => 23h13m38s
[bytes-in] => 31241731
[bytes-out] => 321399768
)
)
答案 0 :(得分:0)
你可以使用array_filter来过滤你想要的相应标准的值;结果将返回过滤后的值;
示例:
$students = array(
array('name' => 'julia', 'age' => 15),
array('name' => 'john', 'age' => 16),
array('name' => 'carlo', 'age' => 14),
array('name' => 'arjay', 'age' => 12),
array('name' => 'francis', 'age' => 11),
array('name' => 'carlo', 'age' => 15),
);
$filtered_students = array_filter($students, function($row) {
if($row['name'] == 'carlo'){
return true;
}
});
print_r($filtered_students);
结果将是:
Array
(
[2] => Array
(
[name] => carlo
[age] => 14
)
[5] => Array
(
[name] => carlo
[age] => 15
)
)
注意到数组上仍然有原始键。如果你想重置计数,只需重新分配;
$filtered_students = array_values($filtered_students);
结果:
Array
(
[0] => Array
(
[name] => carlo
[age] => 14
)
[1] => Array
(
[name] => carlo
[age] => 15
)
)
答案 1 :(得分:0)
试试这个:
foreach( $ARRAY as $value ){
if( $value['name] == 'davies' ) {
echo $value['server'] . '<br /'>;
// And anything else you'd want to echo.
}
}
答案 2 :(得分:0)
编写一个循环遍历数组的函数,并返回记录字段和值与搜索条件匹配的元素记录
function returnRecord($Array, $field, $value) {
foreach ($Array as $record) {
if ($record[$field] && $record[$field] == $value) {
return $record;
}
}
return undef;
}
// Test run
$Array = array(
array('name' => 'davies', '.id' => '*2'),
array('name' => 'eric', '.id' => '*3'),
array('name' => 'teck', '.id' => '*4'),
array('name' => 'andy', '.id' => '*5')
);
$record = returnRecord($Array, 'name', 'davies');
if ($record) {
echo "NAME: ".$record['name'];
echo "\n";
echo "ID: ".$record['.id'];
echo "\n";
}
else {
echo "Record not found";
}