• Hi I am trying to loop through an array of objects that looks like this

    $categories = array(
    [0]=> { feature: 'accounting' },
    [1]=> { industry : 'service'}
    );
    
    $categories_copy = [];
    
    foreach ($categories as $key => $value) {
    		
    		array_push($categories_copy, $value);
    		
    	}
    

    When I try to push it, the $value is the whole { feature : ‘accounting’ } and the $key is just 0, 1 ….

    Is there a better way to loop through it so I can access the key/value pair as $key being feature and $value being ‘accounting’. Looking to get this dynamically cause the key’s may change

Viewing 3 replies - 1 through 3 (of 3 total)
  • The value of $value in your example is the object itself, not the value of the objects data.

    If you are 100% sure that your objects will only have one value available like that you can try something like this:

    foreach ($categories as $i => $object) {
        $values = get_object_vars ($object);
    
        foreach ($values as $key => $val) {
            array_push ($categories_copy, $val);
        }
    }

    However, if you’re going to ever have more than one value in each object you’re going to have to figure out which value you want to get. That will be a bit more difficult as the keys for your objects seem to change as per your example.

    Thread Starter shuangmiles

    (@shuangmiles)

    Ahh that didn’t work, I keep getting a critical error when trying it

    So what is the error message? Some basic debugging will help you to find out what is wrong.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Access key and value from an array of objects’ is closed to new replies.