数组键上的模式匹配

Oli*_*ver 5 php arrays key wildcard pattern-matching

我需要从这个数组中获取股票价值:

Array ( 
[stock0] => 1
[stockdate0] => 
[stock1] => 3 
[stockdate1] => apple 
[stock2] => 2 [
stockdate2] => 
) 
Run Code Online (Sandbox Code Playgroud)

我需要在这个数组上进行模式匹配,其中数组键="stock"+ 1个通配符.我已经尝试使用数组过滤器函数来获取PHP手册上的所有其他值,但空值似乎将其抛弃.我尝试了很多不同的东西,但没有任何工作.

可以这样做吗?

Chr*_*ish 2

array_filter 无权访问密钥,因此不是适合您工作的工具。

我相信你想要做的是这样的:

$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;
}
Run Code Online (Sandbox Code Playgroud)

现在 $stockList 看起来像这样:

Array ( 
[0] => 1
[1] => 3 
[2] => 2 
)
Run Code Online (Sandbox Code Playgroud)

您可能需要对此大惊小怪,但我认为这就是您所要求的。

然而,如果您可以选择的话,您确实应该遵循杰夫·奥伯的建议。