1

Hi I have this array coming in:

$myRegionData =
    array ( 
    [0] => stdClass Object 
        ( 
            [howmuch] => 1 
            [country] => ID 
            [state] => JAWA BARAT 

           ) 
    [1] => stdClass Object 
        ( 
            [howmuch] => 1 
            [country] => RO 
            [state] => BUCURESTI 
         ) 

    [2] => stdClass Object 
        ( 
            [howmuch] => 2 
            [country] => US 
            [state] => CALIFORNIA 
         ) 

    [3] => stdClass Object 
        ( 
            [howmuch] => 1 
            [country] => US 
            [state] => TEXAS  
          )
      ) 

Im trying to group the array outuput as such

ID
 JAWA BARAT (1) 
RO
 BUCURESTI (1)
US
 CALIFORNIA (2)
 TEXAS (1)

I have tried Key value associations, i Loops etc.. and I can seem to combine the US states in the display.

Any advice would be greatly appreciated

1 Answer 1

1

I'd reorganise it by country first to make things easier:

// will hold the re-indexed array
$indexed = array();

// store each state's object under the country identifier
foreach($myRegionData as $object) {
    if(!isset($indexed[$object->country])) {
        $indexed[$object->country] = array();
    }

    $indexed[$object->country][] = $object;
}

// output the data
foreach($indexed as $country => $states) {
    echo $country, "\n";
    foreach($states as $state) {
        printf(" %s (%u)\n", $state->state, $state->howmuch);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works well. Can you help me understand this: $indexed[$object->country][] = $object;
$indexed[$object->country] is an array, and [] appends an element to the end of it. It's equivalent to array_push().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.