如何在数组中搜索特定值?

时间:2019-03-14 14:59:12

标签: php

我需要一些有关如何从搜索框中搜索数组的帮助。

假设我搜索$ticker并写成BTC

然后它将打印出:

The last known currency for BTC is 57 

我只希望它打印出$ k3个值。

感谢您是否愿意花时间指导我正确的方向:)

<form method="POST" action="">
    <input type="text" name="Searcharray" name="searcharray">
    <input type="submit" value="Search" name="searcharray">
</form>

<?php

$ticker = array(
    0 => "BTC",
    1 => "ETH",
    2 => "LTC",
    3 => "XMR",
    4 => "XRP"
);
$name = array(
    0 => "Bitcoin",
    1 => "Ethereum",
    2 => "Litecoin",
    3 => "Monero",
    4 => "Ripple"
);
$k1 = array(
    0 => 1,
    1 => 2,
    2 => 3,
    3 => 4,
    4 => 5
);
$k2 = array(
    0 => 11,
    1 => 12,
    2 => 13,
    3 => 14,
    4 => 15
);
$k3 = array(
    0 => 17,
    1 => 27,
    2 => 37,
    3 => 47,
    4 => 57
);
?>

2 个答案:

答案 0 :(得分:0)

array_search会有所帮助-http://php.net/manual/de/function.array-search.php

$index = array_search('BTC', $ticker);
$value = $k3[$index];

为什么不建立这样的结构?

$data = [
  'BTC' => [
     'name' => 'Bitcoin',
     'k1' => 1,
     'k2' => 11,
     'k3' => 17
  ], ...
];

那么它将是:

$value = $data['BTC']['k3'];

答案 1 :(得分:0)

$index = array_search("BTC", $ticker);
if ($index !== FALSE) {
    $currency = $k3[$index];
    echo "The last known currency of BTC is $currency";
}

但是,如果使用二维关联数组,事情会更容易:

$data = [
    "BTC" => ["name" => "Bitcoin", "k1" => 1, "k2" => 11, "k3" => 17],
    "ETH" => ["name" => "Ethereum", "k1" => 2, "k2" => 12, "k3" => 27],
    ...
];

那么您可以做:

if (isset($data["BTC"])) {
    $currency = $data["BTC"]["k3"];
    echo "The last known currency of BTC is $currency";
}