概要
閲覧数:1294
投稿日:2016-06-27
更新日:2016-06-27
stdClassで、指摘キー毎の数をカウント後、新たなキーとして追加
☆処理内容
・area毎に名寄せ
・areaの値毎の数をカウントして、countキーとして追加
・user_idキーは不要なので削除
コード
$users[] = (object)['user_id' => 'a','area' => '東京',]; $users[] = (object)['user_id' => 'b','area' => '大阪',]; $users[] = (object)['user_id' => 'c','area' => '大阪',]; print_r($users); $tmp = array(); foreach ($users as $obj) { $area = $obj->area; if (array_key_exists($area, $tmp)) { $tmp[$area]++; } else { $tmp[$area] = 1; } } //中間結果表示 print_r($tmp); $result = array(); foreach ($tmp as $area => $num) { $result[] = (object) array( 'count' => $num, 'area' => $area ); } //結果表示 print_r($result);
結果
Array ( [0] => stdClass Object ( [user_id] => a [area] => 東京 ) [1] => stdClass Object ( [user_id] => b [area] => 大阪 ) [2] => stdClass Object ( [user_id] => c [area] => 大阪 ) ) Array ( [東京] => 1 [大阪] => 2 ) Array ( [0] => stdClass Object ( [count] => 1 [area] => 東京 ) [1] => stdClass Object ( [count] => 2 [area] => 大阪 ) )