[英]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
让我们说我搜索
$ticker
并写BTC
It will then print out: 然后打印出来:
The last known currency for BTC is 57
I only want it to print out $k3 values. 我只想打印出$ k3值。
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 array_search会有所帮助 - 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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.