php数组过滤由多个数组中的键定义的值

时间:2014-08-06 18:27:35

标签: php arrays foreach

您好我正在尝试解决以下问题。我有一些自我解释的代码,但我需要添加几行代码 我想通过键值[1]过滤键值定义的较低值数组(在本例中为[2])。因此,如果我有3个包含值[1]且值为100的数组,那么应该通过键[2]过滤数组。

到目前为止我的代码示例:

foreach($data as $line) {
if(substr($line,0,1)=="A") {
if(!$first) {
$parts = explode(chr(9), $line);
list($num1, $num2) = explode('_', $parts[1]); //code comes first / tested and works
$parts[2] = isset($num2) ? $num2 : $parts[2]; //it replaces key[2] with _* (1,2,3)

//then this will follow
$pos = strpos($parts[1], '_');  // this will remove all _* from key [1] if they exist
if($pos !== false) $parts[1] = substr($parts[1], 0, $pos); // tested and works

//echo "<pre>"; print_r($parts); echo "</pre>";

//need code to filter the arrays defined by key [1] via key [2] here?

例如,如果我的代码之后有多个数组,那么:

Array
(
[0] => A
[1] => 100
[2] => 1
[3] => 1184
[4] => 0
)

Array
(
[0] => A
[1] => 100
[2] => 2
[3] => 1185
[4] => 0
)

Array
(
[0] => A
[1] => 100
[2] => 3
[3] => 1186
[4] => 0
)

Array
(
[0] => A
[1] => 101
[2] => 1
[3] => 1187
[4] => 0
)

Array
(
[0] => A
[1] => 101
[2] => 2
[3] => 1188
[4] => 0
)

Array
(
[0] => A
[1] => 302
[2] => 0
[3] => 1161
[4] => 0
)

经过一些过滤数组的代码后,最终的结果将是:

Array
(
[0] => A
[1] => 100
[2] => 3
[3] => 1186
[4] => 0
)

Array
(
[0] => A
[1] => 101
[2] => 2
[3] => 1188
[4] => 0
)

Array
(
[0] => A
[1] => 302
[2] => 0
[3] => 1161
[4] => 0
)

请问我可以提供一些帮助,它只需要几行,我不是程序员,但我想完成这个项目。

2 个答案:

答案 0 :(得分:0)

试试这个:

$array = array("A", "100_1", 0, 1184, 0);
$array = array_map(
    function($str) {
        return preg_replace_callback('/([\d]+)\_([1-3])/', function($matches){ return $matches[1] + $matches[2]-1;}, $str);
    },
    $array
);

print_r($array)

答案 1 :(得分:0)

试试这个:

$part = array(); 
foreach ($parts as $key => $value) { 
if (isset($part[$value[1]])) { 
if ($parts[$part[$value[1]]][0][2] < $value[0][2]) { 
$part[$value[1]] = $key; 
} 
} else { 
$part[$value[1]] = $key;

//echo "<pre>"; print_r($part); echo "</pre>";
}
}

我改变了答案,因为它不是我想要的,但这是。