不希望Array ito结合值

时间:2014-12-10 15:27:55

标签: php arrays

我在PHP中有一个类似于:

的数组
Array ( [2099:360] => 6-3.25 [2130:361] => 4-2.5 [2099:362] => 14-8.75 ) 

请注意,有两个键是2099,一个是2130.我有一个foreach删除冒号后的所有内容。 $ drop是我的数组

$a = array();
foreach ($drop as $part=>$drop_a){
    $ex_part = explode(":", $part);
    $a[$ex_part[0]] = $drop_a;
}

print_r($a);

但是当我打印$ a时,它只显示最近的2099值?

Array ( [2099] => 14-8.75 [2130] => 4-2.5 )

任何继承?如何让它显示所有值?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用多维数组来存储此策略:

$a = array();
foreach ($drop as $part=>$drop_a){
    $ex_part = explode(":", $part);
    if (isset($a[$ex_part[0]])) {
        $a[$ex_part[0]][] = $drop_a;
    } else {
        $a[$ex_part[0]] = array($drop_a);
    }
}

您的结果数据集会有所不同:

Array ( [2099] => Array ( [0] => 6-3.25 [1] => 14-8.75) [2130] => Array ( [0] => 4-2.5 ) )

在冒号:

之后保留第二部分可能对您有益
$a = array();
foreach ($drop as $part=>$drop_a){
    $ex_part = explode(":", $part);
    if (isset($a[$ex_part[0]])) {
        $a[$ex_part[0]][$ex_part[1]] = $drop_a;
    } else {
        $a[$ex_part[0]] = array($ex_part[1] => $drop_a);
    }
}

现在你的结果更有意义了:

Array ( [2099] => Array ( [360] => 6-3.25 [362] => 14-8.75) [2130] => Array ( [361] => 4-2.5 ) )

最后,如果已经占用了一个替代的键命名策略,你可以使用它:

$a = array();
foreach ($drop as $part=>$drop_a){
    $ex_part = explode(":", $part);
    if (isset($a[$ex_part[0]])) {
        $a[altName($ex_part[0], $a)] = $drop_a;
    } else {
        $a[$ex_part[0]] = $drop_a;
    }
}

function altName($key, $array) {
    $key++; // Or however you want to do an alternative naming strategy
    if (isset($array[$key])) {
        return altName($key, $array); // This will eventually resolve - but be careful with the recursion
    }
    return $key;
}

返回:

Array
(
    [2099] => 6-3.25
    [2130] => 4-2.5
    [2100] => 14-8.75
)

答案 1 :(得分:0)

每个条目基本上都有一个键和一个子键,所以只需将它们放在一个多维数组中:

$a = array();
foreach ($drop as $key => $val) {
    list($key, $subKey) = explode(':', $key);
    $a[$key][$subKey] = $val;
}

给你:

Array
(
    [2099] => Array
        (
            [360] => 6-3.25
            [362] => 14-8.75
        )

    [2130] => Array
        (
            [361] => 4-2.5
        )

)

您可以通过嵌套循环来遍历多维数组:

foreach ($a as $key => $subKeys) {
    foreach ($subKeys as $subKey => $val) {
        echo "$key contains $subKey (value of $val) <br>";
    }
}