Php - 组合具有相同值的单个数组的行

时间:2018-01-23 16:17:05

标签: php arrays

基本上我有这个数组:

$foo[0] = array("name" => "A", "apples" => "2");
$foo[1] = array("name" => "B", "apples" => "4");
$foo[2] = array("name" => "C", "apples" => "6");
$foo[3] = array("name" => "A", "apples" => "3");
$foo[4] = array("name" => "B", "apples" => "5");
$foo[5] = array("name" => "C", "apples" => "7");

我想要这个:

$foo[0] = array("name" => "A", "apple1" => "2", "apple2" => "3");
$foo[1] = array("name" => "B", "apple1" => "4", "apple2" => "5");
$foo[2] = array("name" => "C", "apple1" => "6", "apple2" => "7");

3 个答案:

答案 0 :(得分:1)

只要您使用数组,就可以使用数组而不是编号字符串,如:

$foo[0] = array("name" => "A", "apples" => array("2", "3"));

name值循环并索引结果,并将apples值动态附加到apples数组:

foreach($foo as $v) {
    $result[$v['name']]['name'] = $v['name'];
    $result[$v['name']]['apples'][] = $v['apples'];
}

然后如果需要重新索引:

$result = array_values($result);

答案 1 :(得分:0)

您可以执行经典 foreach循环:

$foo[0] = array("name" => "A", "apples" => "2");
$foo[1] = array("name" => "B", "apples" => "4");
$foo[2] = array("name" => "C", "apples" => "6");
$foo[3] = array("name" => "A", "apples" => "3");
$foo[4] = array("name" => "B", "apples" => "5");
$foo[5] = array("name" => "C", "apples" => "7");

$result = array();
foreach( $foo as $value ) {
    if ( !isset( $result[ $value[ "name" ] ] ) ) {
        $result[ $value[ "name" ] ] = array();
        $result[ $value[ "name" ] ][ "name" ] = $value[ "name" ];
        $result[ $value[ "name" ] ][ "apple1" ] = $value[ "apples" ];
    } else {
        $cnt = count( $result[ $value[ "name" ] ] );
        $result[ $value[ "name" ] ][ "apple" . $cnt ] = $value[ "apples" ];
    }
}

//returns all the values from the array and indexes the array numerically.
$result = array_values( $result );

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

这将导致:

Array
(
    [0] => Array
        (
            [name] => A
            [apple1] => 2
            [apple2] => 3
        )

    [1] => Array
        (
            [name] => B
            [apple1] => 4
            [apple2] => 5
        )

    [2] => Array
        (
            [name] => C
            [apple1] => 6
            [apple2] => 7
        )

)

答案 2 :(得分:0)

这些结果来自数据库吗?

如果是这样的话,你可以用一些PDO常量的组合在一行中做到这一点:https://phpdelusions.net/pdo/fetch_modes#FETCH_UNIQUE

我会查看PDO::FETCH_UNIQUEPDO::FETCH_GROUP,它们也可以合并为PDO::FETCH_UNIQUE|PDO::FETCH_GROUP

如果没有,则查询本身也可以使用GROUP BY

生成此信息