Re: joining array values

From: Date: Thu, 12 May 2005 18:59:23 +0000
Subject: Re: joining array values
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-215060@lists.php.net to get a copy of this message
Merlin wrote:
Brent Baisley wrote:
Use the id number as the array key and a simple loop should join everything together. for($i=0; $i<count($result['id']); $i++) {
    $id = $result['id'][$i];
    $text = $result['text'][$i];
    $relevance = $result['relevance'][$i];
        $resultSummary[$id]['id'] = $id;
    if ( isset($resultSummary[$id]['text']) ) {
        $resultSummary[$id]['text'] .= ' '.$text;
    } else {
        $resultSummary[$id]['text'] = $text;
    }
    if ( isset($resultSummary[$id]['rel']) ) {
        $resultSummary[$id]['relevance'] += ' '.$relevance;
    } else {
        $resultSummary[$id]['relevance'] = $relevance;
    }
}
...
For example:
id    text    relevance
23    ok    2
42    joel    1
23    php    1
Desired output:
id    text    relevance
23    ok php    3
42    joel    1
Has anybody an ide how to do that? Thank you for any help, Merlin
....
Hi Brent, thank you for that excellent example. I tried to get that working in a similar way but failed. However, you brought in knowledge which puts me into trouble. How can I output those arrays if they are the other way around? I used to do it like this: for ($i=0;$i<count($result[id]);$i++){
    echo $result[id][$i];
    echo $result[text][$i];
} Now the array is the other way around, plus the array $resultSummary[$id]['id'] is not a 1,2,3 thing but there are missing values?! I need those Id's to create proper links from the output.
have you tried foreach? e.g. foreach ($resultSummary as $id => $vals) { print_r( $vals ); // do some stuff. }
Can you shed some more light on this?
it might help to know that actually the '1,2,3 thing' is a '0,1,2 thing' - sequential (int) keys are always zero based. read: http://nl2.php.net/manual/en/language.types.array.php http://nl2.php.net/array http://nl2.php.net/foreach http://nl2.php.net/manual/en/language.control-structures.php good luck.

« previous php.general (#215060) next »