简体   繁体   中英

ErrorException Array to string conversion Laravel 8

I have JSON-formed data and it is converted into the array. But I cannot iterate the array and fetch the data, it shows an error.

ErrorException Array to string conversion

Data:

Array
(
    [posts] => Array
        (
            [0] => Array
                (
                    [post_id] => 5083755625086176
                    [text] => Carry on the Trend!
                    [links] => Array
                        (
                            [0] => Array
                                (
                                    [link] => https:// .........
                                    [text] => xyz
                                )

                        [1] => Array
                            (
                                [link] => https:// .........
                                [text] => xyz
                            )
                         )
                )

        [1] => Array
            (
                [post_id] => 5083755138419558
                [text] => Carry on the Trend!
                [links] => Array
                    (
                        [0] => Array
                            (
                                [link] => https:// .........
                                [text] => xyz
                            )

                        [1] => Array
                            (
                                [link] => https:// .........
                                [text] => xyz
                            )
                      )
             )

        [2] => .........
            
      )
)

Controller

foreach($array['posts'] as $scrapeData){
        $product = new Product;
        $product->id= $scrapeData['post_id'];
        $product->description = $scrapeData['text'];

        $product->save();
    }

    foreach($array['posts']['links'] as $datalink){
        $images_links = new ProductImage;
        $images_links->link= $datalink['link'];
       
        $images_links->save();
    }

You have to move your second loop into the first to iterate the links :

     foreach($array['posts'] as $scrapeData){
        $product = new Product;
        $product->id= $scrapeData['post_id'];
        $product->description = $scrapeData['text'];
        $product->save();

        foreach($scrapeData['links'] as $datalink) {
            $images_links = new ProductImage;
            $images_links->link= $datalink['link'];
            $images_links->save();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM