Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FnF1's avatar
Level 1

How to access an object in an array of objects? (json)

Goal is to add "municipality,province" in an array so I can display it in my blade file.

FindDoctor.php

class FindDoctor extends Controller
{
    function getLocations()
    {
        $data = Http::get('https://raw.githubusercontent.com/flores-jacob/philippine-regions-provinces-cities-municipalities-barangays/master/philippine_provinces_cities_municipalities_and_barangays_2019v2.json')->json();
        $arr = [];

        foreach ($data as $place) {
            foreach ($place['region_name'] as $region) { <--- error points here
                foreach ($region['province_list'] as $province) {
                    foreach ($province['municipality_list'] as $municipality) {
                        array_push($arr, $municipality . ", " . $province);
                    }
                }
            }
        }

        return $arr;
    }
}

The API returns something like:

{
  "01": {
    "region_name": "REGION I",
    "province_list": {
      "ILOCOS NORTE": {
        "municipality_list": {
          "ADAMS": {
            "barangay_list": [
              "ADAMS (POB.)"
            ]
          },
          "BACARRA": {
            "barangay_list": [
              ...
           ]
         },
      }
   }
}

ErrorException: foreach() argument must be of type array|object, string given

How do I access the objects of munipality_list?

0 likes
7 replies
kokoshneta's avatar

Uh… in your sample JSON from the API, region_name is a string, so how are you expecting foreach to work exactly?

Just remove the foreach($place['region_name'] as $region) part and change $region['province_list'] to $place['province_list'].

Of course, that won’t fix the error that you’re later on trying to concatenate an array element with its own parent array – that won’t work. Also, your sample JSON is weird. The main collection of places as well as all the xyz_list properties should be arrays if the API behaves like a normal API. This is what you’d expect it to look like:

{
	"data": [
		{
			"region_name": "REGION I",
			"province_list": [
				{
					"province_name": "ILOCOS NORTE",
					"municipality_list": [
						{
							"municipality_name": "ADAMS",
							"barangay_list": [
								"ADAMS (POB.)"
							]
						},

						{
							"municipality_name": "BACARRA",
							"barangay_list": [
								"..."
							]
						}
					]
				}
			]
		}
	]
}
FnF1's avatar
Level 1

@kokoshneta Hi, thanks for taking time to give me an answer. I did what you suggested; it fixed the foreEach() error but got an Array to string conversion error like you said I would.

I also agree with the API being weird. Unfortunately, this is the only one I found that is still working to this day. If worse comes to worst, I'll just list everything manually in a file and load it into the controller.

Thanks again.

kokoshneta's avatar

@FnF1 But your desired output would be something like this?

[
	"ADAMS, ILOCOS NORTE",
	"BACARRA, ILOCOS NORTE"
	...
]
kokoshneta's avatar
Level 27

@FnF1 Yeah, the weirdness of the API response makes it trickier than it ought to be. This is the least clumsy and most Laravel-like way I can think of:

class FindDoctor extends Controller {
	public function getLocations() {
		$arr = [];
		$data = Http::get('https://raw.githubusercontent.com/flores-jacob/philippine-regions-provinces-cities-municipalities-barangays/master/philippine_provinces_cities_municipalities_and_barangays_2019v2.json')
			->collect()
			->flatten(1)
			->filter(fn($item) => \is_array($item))
			->flatMap(fn($v) => $v);

		foreach ($data as $province => $municipalities) {
			foreach ($municipalities['municipality_list'] as $municipality => $barangays) {
				$arr[] = "{$municipality}, {$province}";
			}
		}

		return $arr;
	}
}
FnF1's avatar
Level 1

@kokoshneta Thank you so much for this. It worked like a charm. I see some unfamiliar functions you used. I'm gonna study em to understand how you did it. Thank you again!

kokoshneta's avatar

@FnF1 Those are collection methods. They sometimes make it easier to manipulate arrays. Note how I changed the ->json() call to ->collect() on the Http::get() response – that makes it return a Laravel collection instead of a plain array, which gives you these extra functions to play around with.

1 like

Please or to participate in this conversation.