0

I have different 'spots' inside multiple arrays against each city name. Like Houston has two arrays each with a different 'spots' value. What I want to do is add those two 'spots' values against Houston or any cities name, inside maybe a new array. So that when I want to access 'spots' I get the total of 'spots' of a single city.

This is the code inside the controller:

foreach ($request->city as $city) {
                $citySpots[$city] = Controller::select('spots')
                                    ->where('city', $city)
                                    ->get()
                                    ->toArray();
            }

dd($citySpots);

dd value:

array:2 [▼
  "Houston" => array:2 [▼
    0 => array:1 [▼
      "spots" => "20"
    ]
    1 => array:1 [▼
      "spots" => "10"
    ]
  ]
  "New York" => array:1 [▼
    0 => array:1 [▼
      "spots" => "500"
    ]
  ]
]

1 Answer 1

1

each city has visited spots , i am suggesting you count the spots and then groupby the name of the city :

it goes somthing like this

foreach ($request->city as $city) {
                $citySpots[$city] = DB::table('table_name') 
                                    ->select(DB::raw('sum(spots) as spots'))
                                    ->where('city', $city)
                                    ->groupBy('city')
                                    ->get()
                                    ->toArray();
            }

dd($citySpots);

dd should be

array:2 [▼
  "Houston" => array:1 [▼
    0 => array:1 [▼
      "spots" => "30"
    ]
  ]
  "New York" => array:1 [▼
    0 => array:1 [▼
      "spots" => "500"
    ]
  ]
]
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you sir you are a savior. the only thing is that spot is object now ``` "Houston" => array:1 [▼ 0 => {#1282 ▼ +"spot": 30.0 } ] ``` Is it possible to convert it to array?
and Is it possible to achieve all this with Eloquent?
ig not with eloquent directly , try this instead of toArray() : ->map(function ($item) {return array_merge(...$item->toArray());
Thank you. much appreciated 😊

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.