PHP - 数组值输出并获得类似的值

时间:2013-11-20 22:20:40

标签: php

我有一个像这样的数组

Array ( [item1] => pack1 [amount1] => 1 [price1] => 25 [amount2] => 1 [price2] => 45 [item3] => pack3 [amount3] => 4 [price3] => 65 [sender] => Submit )

我需要获取值item1& item3从数组中删除,然后用

删除它们上的项目
str_replace

然后用

找到最大数字
max

只是第一部分是最艰难的,任何想法?

2 个答案:

答案 0 :(得分:0)

foreach通过数组,如果键包含item,则获取/设置值。同时检查该值以查看它是否大于之前的值以获得最大值

答案 1 :(得分:0)

$a = array( "item1" => "pack1", "amount1" => 1, "price1" => 25, "amount2" => 1, "price2" => 45, "item3" => "pack3");
$b = array();
$pattern = '/item[1-9]/';
$max_index = 0;
foreach($a as $key => $value){
    if(preg_match($pattern, $key, $matches, PREG_OFFSET_CAPTURE)){
        $index = str_replace("item","",$key);
        $b[$index] = $value;
        if($index > $max_index){
            $max_index = $index;
        }
    }
}
$max_value = $b[$max_index];
echo $max_value;