Search code examples
arrayslaravelkeyunion

how to get the value of an object in array using laravel?


I want to change the output of this array to another array using laravel. here is the actual array : the actuel array

array:4 [▼ 0 => {#2569 ▶ +"count": 6 } 1 => {#2578 ▶ +"count": 7 } 2 => {#2577 ▶ +"count": 1 } 3 => {#2576 ▶ +"count": 0 } ]

what I want to display instead :

array:4 [ 'A':6, 'B':7, 'C':0, 'D':1 ]

here is my source code.

$filter = ["A","B","C","D"];
if(user()->hasRole('admin')){
                   $projects = DB::table('projects AS p')->select(DB::raw('count(p.id) as count'))->where('p.alphabet','=','A')
                       ->union(DB::table('projects AS p')->select(DB::raw('count(p.id) as count'))->where('p.alphabet','=','B'))
                       ->union(DB::table('projects AS p')->select(DB::raw('count(p.id) as count'))->where('p.alphabet','=','C'))
                   ->union(DB::table('projects AS D')->select(DB::raw('count(p.id) as count'))->where('p.alphabet','=','C'));}
return ($projects->get()->toArray());

the output of print_r($projects->get()->toArray()) is : Array ( [0] => stdClass Object ( [count] => 6 ) [1] => stdClass Object ( [count] => 7 ) [2] => stdClass Object ( [count] => 1 ) [3] => stdClass Object ( [count] => 0 ) )

any help please?


Solution

  • if(user()->hasRole('admin')){
                       $projects = DB::table('projects AS p')->select(DB::raw(" 'A' as alphabet, count(p.id) as occurrences"))->where('p.alphabet','=','A')
                           ->union(DB::table('projects AS p')->select(DB::raw(" 'B' as alphabet, count(p.id) as B"))->where('p.alphabet','=','B'))
                           ->union(DB::table('projects AS p')->select(DB::raw(" 'C' as alphabet, count(p.id) as C"))->where('p.alphabet','=','C'))
                           ->union(DB::table('projects AS p')->select(DB::raw(" 'D' as alphabet, count(p.id) as D"))->where('p.alphabet','=','D'));
    
                    $result=$projects->get()->toArray();
                    $newArr = array();
                    foreach ($result as $pair) {
                        $newArr[$pair->alphabet] = $pair->occurrences;
                    }
                    dd($newArr);