数组键上的模式匹配 [英] Pattern Match on a Array Key
问题描述
我需要从这个数组中获取股票价值:
I need to get the stock values out of this array:
Array (
[stock0] => 1
[stockdate0] =>
[stock1] => 3
[stockdate1] => apple
[stock2] => 2 [
stockdate2] =>
)
我需要对该数组进行模式匹配,其中数组键 = "stock" + 1 个通配符.我曾尝试使用数组过滤器函数来获取 PHP 手册上的所有其他值,但是空值似乎把它扔掉了.我尝试了很多我发现的不同的东西,但没有任何效果.
I need to pattern match on this array, where the array key = "stock" + 1 wildcard character. I have tried using the array filter function to get every other value on the PHP manual but the empty values seem to throw it out. I tried alot of different things I found but nothing is working.
这能做到吗?
推荐答案
array_filter 无法访问密钥,因此不是适合您工作的工具.
array_filter does not have access to the key and therefore is not the right tool for your job.
我相信你想要做的是:
$stocks = Array (
"stock0" => 1,
"stockdate0" => '',
"stock1" => 3,
"stockdate1" => 'apple',
"stock2" => 2,
"stockdate2" => ''
);
$stockList = array(); //Your list of "stocks" indexed by the number found at the end of "stock"
foreach ($stocks as $stockKey => $stock)
{
sscanf($stockKey,"stock%d", &stockId); // scan into a formatted string and return values passed by reference
if ($stockId !== false)
$stockList[$stockId] = $stock;
}
现在 $stockList 看起来像这样:
Now $stockList looks like this:
Array (
[0] => 1
[1] => 3
[2] => 2
)
您可能需要大惊小怪,但我认为这就是您要的.
You may need to fuss with it a bit, but I think this is what you are asking for.
但是,如果您可以选择这样做,您确实应该遵循 Jeff Ober 的建议.
HOWEVER, you really should be following Jeff Ober's advice if you have the option to do so.
这篇关于数组键上的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!