php 移除平面数组中下一个元素不是价格值的元素

wbgh16ku  于 10个月前  发布在  PHP
关注(0)|答案(8)|浏览(57)

我有一个大数组的刮名字和价格类似于以下:

Array(
  [0] => apple3
  [1] => £0.40
  [2] => banana6
  [3] => £1.80
  [4] => lemon
  [5] => grape
  [6] => pear5
  [7] => melon4
  [8] => £2.32
  [9] => kiwi
  [10] => £0.50
)

我想删除没有立即跟随价格的水果名称。在上面的例子中,这将删除:[4] => lemon [5] => grape [6] => pear5导致以下输出:

Array(
  [0] => apple3
  [1] => £0.40
  [2] => banana6
  [3] => £1.80
  [7] => melon4
  [8] => £2.32
  [9] => kiwi
  [10] => £0.50
)

如果需要将数组转换为字符串,这对我来说不是问题,也不是为了帮助正则表达式搜索而在数组项之间添加值。到目前为止,我还无法找到正确的正则表达式来使用preg_match()preg_replace()来实现这一点。
最重要的因素是需要保持水果和价格的顺序,以便我在稍后的阶段将其转换为水果和价格的关联数组。

hpxqektj

hpxqektj1#

为什么要使用正则表达式?这可以通过一个简单的foreach循环来实现,在循环中迭代数组并删除名称后面的名称:

$lastWasPrice = true; // was the last item a price?
foreach ($array as $k => $v) {
    if (ctype_alpha($v)) {
        // it's a name
        if (!$lastWasPrice) {
            unset($array[$k]); // name follows name; remove the second
        }
        $lastWasPrice = false;
    }
    else {
        // it's a price
        $lastWasPrice = true;
    }
}
3qpi33ja

3qpi33ja2#

下面的代码同时执行两个任务:去掉没有价值的水果,并将结果转化为一个有价格的水果关联数组。

$arr = array('apple', '£0.40', 'banana', '£1.80', 'lemon', 'grape', 'pear', 'melon', '£2.32', 'kiwi', '£0.50' );

preg_match_all( '/#?([^£][^#]+)#(£\d+\.\d{2})#?/', implode( '#', $arr ), $pairs );
$final = array_combine( $pairs[1], $pairs[2] );

print_r( $final );

首先,将数组转换为字符串,用'#'分隔。正则表达式捕获所有带价格的水果组-每个水果组在结果中存储为一个单独的子组。将它们组合成一个关联数组是一个函数调用。

wfsdck30

wfsdck303#

像这样的东西也许能帮到你

$array = ...;
$index = 0;

while (isset($array[$index + 1])) {
  if (!is_fruit($array[$index + 1])) {
    // Not followed by a fruit, continue to next pair
    $index += 2;
  } else {
    unset($array[$index]);  // Will maintain indices in array
    $index += 1;
  }
}

但没有测试。另外,您需要自己创建函数is_fruit;)

unguejic

unguejic4#

如果不重新格式化它,我认为您不能用preg_matchpreg_replace来实现它--也许可以,但没有想到。
是什么在创建这个数组?如果可能的话,我会把它改成更像:

Array([apple] => £0.40 [banana] => £1.80 [lemon] => [grape] => '' [pear ] => '' [melon  => £2.32 [kiwi] => £0.50)

然后array_filter($array)就是你需要清理它的全部。如果你不能改变原始数组的创建方式,我倾向于从原始数组中创建键/值数组。

eoxn13cs

eoxn13cs5#

只需执行以下操作:

<?php
for($i=0;$i<count($my_array);$i++)
{
if($my_array[$i+1]value=="")
unset($my_array[$i])
}
?>
ycggw6v2

ycggw6v26#

假设$a是你的数组。

function isPrice($str) {
    return (substr($str, 0, 1) == '£');
}
$newA = array();
for($i=0;$i<count($a);$i++) {
    if( isPrice($a[$i]) != isPrice($a[$i+1]) ){
        $newA[] = $a[$i];
    }
}
2uluyalo

2uluyalo7#

尝试将模式**=>([a-zA-Z])替换为=> £0.00 $1**
基本上是搜索有空价格的上下文并插入零英镑。

zaq34kh6

zaq34kh68#

unset() ing相比,有条件地将元素对推入结果数组并保留原始键可能对代码的人类读者更清楚。
代码:(Demo

$array = ['apple3', '£0.40', 'banana6', '£1.80', 'lemon', 'grape', 'pear5', 'melon4', '£2.32', 'kiwi', '£0.50'];

$result = [];
foreach ($array as $i => $v) {
    if (mb_substr($v, 0, 1) === '£') {
        $result[$i - 1] = $array[$i - 1];
        $result[$i] = $v;
    }
}
var_export($result);

相关问题