【问题标题】:Exploding an array values within a foreach loop in PHP在 PHP 中的 foreach 循环中分解数组值
【发布时间】:2022-07-30 14:31:24
【问题描述】:

认为我有一个这样的数组,

$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];

那么,我想explode 使用/ 在数组值之上,如果explode 数组有3 个元素,那么我需要像这样创建一个新数组。

$prefixes = ['PO', 'XY','PO'];

我能知道什么是更好、更有效的方法吗?

这是我目前所拥有的:

$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];


foreach ($code as $v) {
    $nwCode = explode("/",$v);
    if(count($nwCode) == 3) {
      $nwAry[] = $newCode[0];
    }
    
    $nwCode = [];
}

echo '<pre>',print_r ($nwAry).'</pre>';

【问题讨论】:

  • 仅供参考,您可以使用count() 检查explode 结果长度。然后您可以使用if 检查它是否包含3 个项目,最后array_push 将结果存储到累加器或其他东西。好吧,如果你想放弃 foreach,你也可以尝试使用array_map

标签: php arrays loops foreach explode


【解决方案1】:
$code = ['PO/2022/0001', 'abc','xyz','PO2022/0001', 'XY/2022/0002','PO/2022/0232'];

$prefixes = array_map(function($e){
  $nwCode = explode('/', $e);
  if(count($nwCode) == 3)
  {
    return $nwCode[0];
  }
} ,$code);

$prefixes = array_filter($prefixes, function($e){ if(strlen($e) > 0) return true; });

echo "<pre>";
var_dump($prefixes);
echo "</pre>";

array_map 用于获取这些前缀,而array_filter 用于从不匹配的项目中删除空前缀。

你也可以使用array_reduce

$prefixes = array_reduce($code, function($carry, $item){
  $nwCode = explode('/', $item);
  if(count($nwCode) == 3)
  {
    array_push($carry, $nwCode[0]);
  }
  return $carry;
}, array());

【讨论】:

  • 一件事,我是用count($nwCode) &gt; 2)还是count($nwCode) == 3)
  • @TharangaNuwan, count($nwCode) &gt; 2 将返回 true 如果您的 $nwCode 中至少有 3 个项目。您可以使用count($nwCode) == 3 进行完全匹配。很抱歉造成混乱。
【解决方案2】:

因为您想对具有严格格式/签名的字符串执行替换并过滤掉与签名不匹配的元素,所以 PHP 必须提供的最佳工具是 preg_filter()

模式分解:

^              #start of string
[^/]+          #one or more non-slash characters
\K             #forget/release previously matched characters
(?:/[^/]+){2}  #match 2 sets of slash followed by one or more non-slash characters
$              #end of string

代码:(Demo)

var_export(
    preg_filter(
        '~^[^/]+\K(?:/[^/]+){2}$~',
        '',
        $code
    )
);

输出:

array (
  0 => 'PO',
  4 => 'XY',
  5 => 'PO',
)

如果您需要索引键,请在结果数组上调用 array_values()

【讨论】:

    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多