Search code examples
phparrayscpanel

How to loop through an Array in an Object PhP


when I call this Cpanel API $result = $cPanel->execute('uapi', 'DomainInfo', 'list_domains'); to Cpanel Uapi I get the Object value stated below. To display the object, I use var_dump($result);. It works as expected. Then access main_domain values

USING

<?php echo $result->data->main_domain; ?>

I get the correct value for main_domain stated in var_dump below which is main-example.ng

The thing is, I am having trouble looping through addon_domains, subdomains and parked_domains, I tried:

<?php
foreach ($result as $key){  
?>  
<li><?php echo $key->addon_domains; ?></li>
<?php
}
?> 

AND

<?php
foreach ($result as $key){  
?>  
<li><?php echo $key->sub_domains; ?></li>
<?php
}
?> 

But it doesn't work, I get error Array to String conversion please what am I doing wrong.

object(stdClass)#4 (5) { 
["addon_domains"]=> array(9) { 
[0]=> string(12) "example.com" 
[1]=> string(11) "example1.com" 
[2]=> string(11) "example2.com" 
[3]=> string(11) "example3.com" 
[4]=> string(15) "example4.website" 
[5]=> string(15) "example5.xyz" 
[6]=> string(12) "example6.com" 
[7]=> string(13) "example7.com" 
[8]=> string(11) "example8.com" 
} 
["cp_php_magic_include_path.conf"]=> string(1) "1" 
["main_domain"]=> string(16) "main-example.ng" 
["sub_domains"]=> array(10) { 
[0]=> string(19) "uc.example.ng" 
[1]=> string(20) "pos.example1.ng" 
[2]=> string(26) "new-example-team.example1.ng" 
[3]=> string(21) "example.example1.ng" 
[4]=> string(18) "seller.example.com" 
[5]=> string(41) "example-website-dashboard.example.website" 
[6]=> string(30) "forbidden-link.example.website" 
[7]=> string(17) "about.example.com" 
[8]=> string(18) "seller.example.com" 
[9]=> string(19) "shipper.example.com" 
} 
["parked_domains"]=> array(1) { 
[0]=> string(19) "um.example.ng" 
} 
}

Solution

  • So I got the answer from u_mulder in the comment section. To solve, I did.

      foreach ($result->data->sub_domains as $value){  
       echo $value; 
       }
    

    Try that it should solve the problem.