Home > Back-end >  convert std object array to simple php array
convert std object array to simple php array

Time:01-12

my code so far

<?php
foreach($sub_category as $row2){

    $url = 'https://myurl.com';  
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 3);     
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $data = curl_exec($ch);
    curl_close($ch);
   
    echo $name." data = "."<pre>"; print_r($data);
}


?>

This is $data output

Array
(
    [0] => stdClass Object
        (
            [course_title] => 60  Space Facts To Get An A In Astronomy
            [description] =>  60  Space Facts To Get An "A" In Astronomy
            [image] => pexels-pixabay-39896_20210220014840929292735.jpg
            
        )

    [1] => stdClass Object
        (
            
            [course_title] => Learn Chinese
            [description] => Learn Chinese
            [image] => Chinoabc_20211227114307692406780.png
            
        )
 )

I want to convert it to look like below

Array
        (
            [0] => array
                (
                    [course_title] => 60  Space Facts To Get An A In Astronomy
                    [description] =>  60  Space Facts To Get An "A" In Astronomy
                    [image] => pexels-pixabay-39896_20210220014840929292735.jpg
                    
                )
        
            [1] => array
                (
                    
                    [course_title] => Learn Chinese
                    [description] => Learn Chinese
                    [image] => Chinoabc_20211227114307692406780.png
                    
                )
         )

i have tried many answers from here converting array of objects to simple array but it's not working for me

i have tried many answers from already posted questions. my problem is different than any other relevant question posted here

CodePudding user response:

You can use the (array) type cast to convert an object to an equivalent associative array.

$data = array_map(function($x) { return (array)$x; }, $data);

If the original array of objects came from using json_decode(), you can tell it to return associative arrays instead of objects by giving it a true second argument.

$data = json_decode($data, true);
  •  Tags:  
  • Related