4

I'm using PDO to run a mysql query with 2 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 multiple id's later on but for simplicities sake I only have 1 entry with id 489 for now.

I need the 3 arrays (cause of the joins) to be 1 array that 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'd rather have this done in the PHP and not the Query because I dont have control over the queries when I implement this into the live application.

Any help is much appreciated!

cn007b
  • 16,596
  • 7
  • 59
  • 74
Jebble
  • 266
  • 1
  • 11

3 Answers3

1

You can use another container for gathering all batches which share the same id using its keys to transfer them. On initialization, create another container for that vector, then just push them line any normal array value:

$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

Sample Output

Kevin
  • 41,694
  • 12
  • 53
  • 70
0

You can process your array from DB like this:

$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'];
}
2kai
  • 603
  • 4
  • 13
0

I have the same situation, and i solve it through PDO. Here available examples. I reach same result with code:

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

think you should try it...

cn007b
  • 16,596
  • 7
  • 59
  • 74