1

嗨,我有这个数组进来:

$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  
          )
      ) 

我试图将数组输出分组

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

我已经尝试过键值关联、i Loops 等。我似乎可以在显示中结合美国各州。

任何建议将不胜感激

4

1 回答 1

1

我会先按国家/地区对其进行重组,以使事情变得更容易:

// 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);
    }
}
于 2013-09-24T19:29:35.240 回答