在数组的键模式匹配(Pattern Match on a Array Key)

2019-08-22 02:09发布

我需要获得股票价值了此阵:

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

我需要模式匹配该阵列,其中该阵列关键=“股票” + 1通配符上。 我已经使用了滤镜阵列功能,以获取有关PHP手册每隔值尝试,但空值似乎把它扔出去。 我尝试不同的事情,我发现,但没有什么工作很多。

可以这样做?

Answer 1:

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 
)

您可能需要用它来小题大做了一点,但我觉得这是你所要求的东西。

但是,你真的应该是继杰夫·奥伯的建议,如果你有这样做的选项。



Answer 2:

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

我希望我正确解释和你想的股票',1个通配符,那不是一个换行符,然后结束的字符串。



Answer 3:

你应该存储那些为:

Array(
  [0] => Array(
    stock => 1,
    stockdate => ...
  ),
  [1] => Array(
    stock => 3,
    stockdate => apple
  ),
  ...
)


Answer 4:

由于PHP 5.6.0的flag已添加选项array_filter 。 这允许您基于阵列的键,而不是自己的价值观来筛选:

array_filter($items, function ($key) {
  return preg_match('/^stock\d$/', $key);
}, ARRAY_FILTER_USE_KEY);


Answer 5:

# returns array('stock1' => 'foo')
array_flip(preg_grep('#^stock.$#', array_flip(array('stock1' => 'foo', 'stockdate' => 'bar'))))

不知道性能如何好是由于正则表达式和两个框,但优秀的可维护性(无错误狩猎循环)。



Answer 6:

好的工作液:绿色表示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);


文章来源: Pattern Match on a Array Key