How to group these arrays correctly?

I am using PDO to run a mysql query with two joins, and this is the result I get from the database:

Array
(
[0] => Array
    (
        [id] => 489
        [cluster_id] => 
        [label_value_id] => 4
        [label_id] => 1
        [int_value] => 40
    )

[1] => Array
    (
        [id] => 489
        [cluster_id] => 
        [label_value_id] => 6
        [label_id] => 2
        [int_value] => 20
    )

[2] => Array
    (
        [id] => 489
        [cluster_id] => 
        [label_value_id] => 9
        [label_id] => 3
        [int_value] => 10
    )

)

The idea is that there will be several identifiers later, but for simplicity I only have 1 entry with id 489.

I need 3 arrays (reason for merging) to be 1 array, which looks something like this, I want a subarray based on the label-value_id => int_value relationship:

Array
(
[0] => Array
    (
        [id] => 489
        [cluster_id] => 
        [label_value_id] => 4
        [label_id] => 1
        [int_value] => 40
        [vector_data] => Array
        (
            [4] => 40
            [6] => 20
            [9] => 10
        )
    )
)

I would prefer to do this in PHP rather than Query, because I have no control over the queries when I implement this in a direct application.

Any help is much appreciated!

+4
source share
3 answers

, , . vector, :

$result = array();
foreach($array as $values) {
    // initialization
    if(!isset($result[$values['id']])) {
        $result[$values['id']] = $values;
    }

    $result[$values['id']]['vector_data'][$values['label_value_id']] = $values['int_value'];
}

// $result = array_values($result); // optional key reindex

+1

:

$pdo = array(
    array(
        "id" => 489,
        "label_value_id" => 4,
        "int_value" => 40,
    ),
    array(
        "id" => 489,
        "label_value_id" => 6,
        "int_value" => 20,
    ),
    array(
        "id" => 489,
        "label_value_id" => 9,
        "int_value" => 10,
    ),
);

$result = array();
foreach ($pdo as $array) {
    if (!isset($result[$array['id']])) {
        $result[$array['id']] = array(
            "id" => $array['id'],
            "vector_data" => array()
        );
    }

    $result[$array['id']]['vector_data'][$array['label_value_id']] = $array['int_value'];
}
0

I have the same situation, and I solve it through PDO. Examples are available here . I get the same result with the code:

$sth->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);

I think you should try ...

0
source

All Articles