如何从PHP数组中获取指定的行

时间:2016-07-18 21:27:22

标签: php arrays

所以我有一个带输入的数组和表单,我在其中放置一个ID,该ID应该显示数组中的相应行。

到目前为止,我已经做到了这一点:

<?php
$file = 'people.txt';
$people = array();
    $ref = fopen($file, 'r');
    while ($row = fgets($ref, 1024)) {
        $row = explode("|", $row);
        $id = $row[0];
        $name = $row[1];
        $status = $row[2];
        $people[$id] = array('name' => $name, 'status' => $status);
    }
fclose($ref);

foreach($people as $id => $person) {
    if($_GET[person]==$id && $person[status]==1) {
        echo $person[name] . "(" . $id . "): ready";
    }
    if($_GET[person]==$id && $person[status]==0) {
        echo $person[name] . "(" . $id . "): not ready";
    }
    if($_GET[person]!=$id) {
        echo "Person with this ID was not found";
    }
}
?>

这显示了搜索到的ID的正确信息,但它也显示&#34;未找到人员#34;对阵中的每个人。我怎样才能让它只显示与输入匹配的人?

4 个答案:

答案 0 :(得分:4)

循环中不需要AT ALL。如果您已拥有此人的ID,则无需扫描数组中的该ID,只需直接使用即可:

if (isset($people[$id])) {
   ... do stuff with person # $id
} else {
   ... person does not exist
}

答案 1 :(得分:1)

由于您只搜索一个&#34;人ID&#34;,因此您的代码中不需要第二个foreach循环。我建议重构一下以包含更多错误检查,并在PHP中阅读type juggling and casting

我修改了您的代码,以包含一些可以指向正确方向的提示:

<?php

$file = 'people.txt';
$people = array();

$ref = fopen($file, 'r');

while ($row = fgets($ref, 1024)) {
    $row = explode('|', $row);

    if (!isset($row[0]) || !isset($row[1]) || !isset($row[2])) {
        continue;
    }

    $id = (int) $row[0];
    $name = (string) $row[1];
    $status = (int) $row[2];

    $people[$id] = array('name' => $name, 'status' => $status);
}

fclose($ref);

$id = array_key_exists('person', $_GET) ? $_GET['person'] : null;

if (array_key_exists($id, $people)) {
    $person = $people[$id];

    if ($person['status'] === 1) {
        echo $person['name'] . ' (' . $id . '): ready';
    } else {
        echo $person['name'] . ' (' . $id . '): not ready';
    }
} else {
    echo 'Person with ID ' . htmlspecialchars($id) . ' not found';
}

如果您计划将people.txt变大,请考虑将数据存储在MySQL等数据库中。这将消除在每次请求时必须将文件内容读入内存。

答案 2 :(得分:1)

除非您在此代码之后需要将所有人的数组用于其他目的,否则您只能从文件中获取$_GET['person']指示的人员。只需在while循环中添加一个检查。

$person = null;     // initialize person

$ref = fopen($file, 'r');
while ($row = fgets($ref, 1024)) {
    $row = explode("|", $row);
    if ($row[0] == $_GET['person']) {    // only get rows that match the searched id
        $person = array('name' => $row[1], 'status' => $row[2]);
    }
}
fclose($ref);

这将通过避免创建整个文件的数组来减少脚本的内存使用量。这样做的好处显然取决于文件的大小。

(即使你需要整个数组,你仍然可以在while循环的$person块中设置if,同时填充{ {1}}数组。)

然后在该循​​环之后,$people将只是一件事:或者是文件中最后一个匹配行的数组,或$person。这意味着你不必在数组中找到它;您可以输出如下状态信息:

null

答案 3 :(得分:-2)

使用布尔变量来检测您找到的人是否被找到,代码可能是这样的:

// login.js (render process)
var {ipcRenderer} = require('electron')

ipcRenderer.send('login-success') // call this after the user logs in