up vote 0 down vote favorite

Hi,

I currently have an array, created from a database, an example of which looks like the following:

Array(
    [0] => Array (
        objectid => 2,
        name => title,
        value => apple
    ),

    [1] => Array (
        objectid => 2,
        name => colour,
        value => red
    ),

    [2] => Array (
        objectid => 3,
        name => title,
        value => pear
    ),

    [3] => Array (
        objectid => 3,
        name => colour,
        value => green
    )
)

What I would like to do is group all the items in the array by their objectid, and convert the 'name' values into keys and 'value' values into values of an associative array....like below:

Array (
    [0] => Array (
        objectid => 2,
        title => apple,
        colour => red
    ),

    [1] => Array (
        objectid => 3,
        title => pear,
        colour => green
    )
)

I've tried a few things but haven't really got anywhere.. Any ideas? Thanks in advance

link|flag

3 Answers

up vote 0 down vote accepted

This should work with your current setup and should be able to handle as many key-value pairs as available:

<?php

$results = array(
    array('objectid' => 2, 'name' => 'title', 'value' => 'apple'), 
    array('objectid' => 2, 'name' => 'color', 'value' => 'red'),
    array('objectid' => 3, 'name' => 'title', 'value' => 'pear'), 
    array('objectid' => 3, 'name' => 'color', 'value' => 'green'));

$final = array();
foreach ($results as $result) {
    $final[$result['objectid']]['objectid'] = $result['objectid'];
    $final[$result['objectid']][$result['name']] = $result['value'];
}

print_r($final);
link|flag
up vote 0 down vote

It would be easier to have the array keys correspond with your object id, that way you can iterate through your existing array, and add the key-value pairs for each object, like so:

$newArray = array();
foreach ($results as $result) {

    if (!array_key_exists($result['objectid'], $newArray)) {
        $newArray[$result['objectid'] = array();
    }

    foreach ($result as $key => $value) {
        $newArray[$result['objectid'][$key] = $value;
    }
} 
link|flag
up vote 0 down vote

Peter's method is perfectly valid, I just thought I would show a shorter version of the same thing (couldn't do in a comment)

foreach( $array as $obj ) {
    if( !isset( $objects[$obj['objectid']] ) )
        $objects[$obj['objectid']]['objectid'] = $obj['objectid'];

    $objects[$obj['objectid']][$obj['name']] = $obj['value'];
}
link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.