5

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

Array ( 
[stock0] => 1
[stockdate0] => 
[stock1] => 3 
[stockdate1] => apple 
[stock2] => 2 [
stockdate2] => 
) 

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

这可以做到吗?

4

6 回答 6

4
<?php

$foo = 
array ( 
'stock0' => 1,
'stockdate0' => 1,
'stock1' => 3,
'stockdate1' => 2,
);

$keys = array_keys( $foo );
foreach ( $keys as $key ) {
    if ( preg_match( '/stock.$/', $key ) ) {
    var_dump( $key );
    }
}

我希望我的解释正确,你想要'stock',1 个不是换行符的通配符,然后是字符串的结尾。

于 2009-10-20T16:18:22.293 回答
4

您应该将它们存储为:

Array(
  [0] => Array(
    stock => 1,
    stockdate => ...
  ),
  [1] => Array(
    stock => 3,
    stockdate => apple
  ),
  ...
)
于 2009-10-20T16:18:49.857 回答
4

自 PHP 5.6.0 起,该flag选项已添加到array_filter. 这允许您根据数组键而不是其值进行过滤:

array_filter($items, function ($key) {
  return preg_match('/^stock\d$/', $key);
}, ARRAY_FILTER_USE_KEY);
于 2015-01-08T15:53:15.513 回答
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;
}

现在 $stockList 看起来像这样:

Array ( 
[0] => 1
[1] => 3 
[2] => 2 
)

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

但是,如果您可以选择这样做,您确实应该遵循 Jeff Ober 的建议。

于 2009-10-20T18:05:11.523 回答
1
# returns array('stock1' => 'foo')
array_flip(preg_grep('#^stock.$#', array_flip(array('stock1' => 'foo', 'stockdate' => 'bar'))))

由于正则表达式和两次翻转,不确定性能有多好,但可维护性极佳(循环中没有错误搜索)。

于 2013-02-12T17:45:14.413 回答
0

好的工作解决方案:ChronoFish 的绿色!

 $stockList = array();  //Your list of "stocks" indexed by the number found at the end of "stock"

foreach ($stock as $stockKey => $stock)
{
  sscanf($stockKey,"message%d", $stockId);  // scan into a formatted string and return values passed by reference
  if ($stockId !== false) {
     $stockList[$stockId] = $stock;
}

$stockList=array_values($stockList); //straightens array keys out
$stockList = array_slice ($stockList, "0", $count); //gets rid of blank value generated at end of array (where $count = the array's orginal length)
print_r ($stockList);
于 2009-10-21T08:57:08.090 回答