简体   繁体   中英

How can I search an array for specific values?

I need some help with how I can search an array from a search box.

Lets say I search for the $ticker and write BTC

It will then print out:

The last known currency for BTC is 57 

I only want it to print out $k3 values.

Appreciate if you could take your time and guide me in the right direction :)

<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
);
?>

array_search would help - http://php.net/manual/de/function.array-search.php

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

Why dont you make such a structure?:

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

then it would be:

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

But things would be easier if you used a 2-dimensional associative array:

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

Then you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM