Minimizing nested loops in the response of a multi-dimensional array

When using the Facebook Batch request API, I receive a response. Based on my logic, this response is the best one that I can get, and I want to access the root elements "source_id" and "copied_id" inside the [BODY]. My goal is to access them with minimal loops.

Currently, I am utilizing nested loops.

Array(
[0] => Array
    (
        [0] => stdClass Object
            (
                [code] => 200
                [body] => {"copied_adset_id":"15454","ad_object_ids":[{"ad_object_type":"ad_set","source_id":"545454","copied_id":"15454"}]}
            )
        [1] => stdClass Object
            (
                [code] => 200
                [body] => {"copied_adset_id":"1547754","ad_object_ids":[{"ad_object_type":"ad_set","source_id":"566454","copied_id":"1547754"}]}
            )
     )
 [1] => Array
    (
        [0] => stdClass Object
            (
                [code] => 200
                [body] => {"copied_adset_id":"1500454","ad_object_ids":[{"ad_object_type":"ad_set","source_id":"598754","copied_id":"1500454"}]}
            )
        [1] => stdClass Object
            (
                [code] => 200
                [body] => {"copied_adset_id":"78448","ad_object_ids":[{"ad_object_type":"ad_set","source_id":"541230","copied_id":"78448"}]}
            )
     ))

The body contains the JSON response below, which is the decoded JSON response.

stdClass Object(
[copied_adset_id] => 14848
[ad_object_ids] => Array
    (
        [0] => stdClass Object
            (
                [ad_object_type] => ad_set
                [source_id] => 14848
                [copied_id] => 448486
            )

    ))

Answer №1

Here is some code that may be helpful for you:

foreach($arraya as $arrayaresponse) {    
    foreach($arrayaresponse as $copiedarray) {    
        $adsetdata = array();    
        $copiedBody = json_decode($copiedarray->body);    
        $adata['source_id'] = $copiedBody->ad_object_ids[0]->source_id;   
        $adata['copied_id'] = $copiedBody->ad_object_ids[0]->copied_id;   
    }  
 }

Answer №2

If you're working with Laravel, consider refactoring your code to utilize Collections.

Here's a quick example:

$response = [
    [
        (object) [
            'code' => 200, 
            'body' => '{"copied_adset_id":15454,"ad_object_ids": [{"ad_object_type":"ad_set","source_id": 545454,"copied_id": 545}]}'
        ],
        (object) [
            'code' => 200, 
            'body' => '{"copied_adset_id":15454,"ad_object_ids": [{"ad_object_type":"ad_set","source_id": 545454,"copied_id": 545}]}'
        ]  
    ],
    [
        (object) [
            'code' => 200, 
            'body' => '{"copied_adset_id":15454,"ad_object_ids": [{"ad_object_type":"ad_set","source_id": 545454,"copied_id": 545}]}'
        ],
        (object) [
            'code' => 200, 
            'body' => '{"copied_adset_id":15454,"ad_object_ids": [{"ad_object_type":"ad_set","source_id": 545454,"copied_id": 545}]}'
        ]  
    ]  
];

return collect($response)
    ->flatten()
    ->flatMap(function($item) {
        return json_decode($item->body, true)['ad_object_ids'];
    })
    ->map(function($item) {
        return array_only($item, ['source_id', 'copied_id']);
    })
    ->toArray();

The result will be as follows:

array:4 [▼
  0 => array:2 [▼
    "source_id" => 545454
    "copied_id" => 545
  ]
  1 => array:2 [▼
    "source_id" => 545454
    "copied_id" => 545
  ]
  2 => array:2 [▼
    "source_id" => 545454
    "copied_id" => 545
  ]
  3 => array:2 [▼
    "source_id" => 545454
    "copied_id" => 545
  ]
]

Feel free to experiment with this example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble creating a Node.js equivalent to PHP's hash checking functionality

These PHP lines are effective, but I am unable to replicate them in Node. $secret_key = hash('sha256', XXXX, true); $hash = hash_hmac('sha256', YYYY, $secret_key); The documentation states that hash() returns raw binary data, but it a ...

Ways to make asynchronous requests with guzzle without relying on a proxy server

I am attempting to send 100 asynchronous requests to the Instagram website using PHP Guzzle as shown below: $client = new Client(); $promises = []; for($i = 1; $i <= 100; $i++) { $options = ['timeout' => 60]; $promise = $client-&g ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Oops! There seems to be a small hiccup in the code - it looks like there's a syntax error with the word 'layouts'. We were expecting either a comma or a closing

Currently, I am working on enhancing a view within a Laravel project. The entire project can be found on GitHub at https://github.com/wvulibraries/rockefeller-css/tree/trying-searchy/src/project-css. My goal is to detect if a string contains a file name wi ...

"Although AJAX isn't functioning properly, the traditional form submission method is still operational

Does anyone know why this AJAX request is not sending the required data? The request is successful and triggers an alert, but no data is being sent. A standard ('#formid').submit function works, but it causes a page refresh. I need to achieve ...

Extract the last word from the URL and remove any unnecessary components

Big shoutout to the amazing individuals who have provided assistance on another thread: Retrieve final word from URL following a forward slash in PHP Now, I am encountering a new dilemma. How can I accomplish this task in PHP: If $last_word also contai ...

Ways to increase the value of a multidimensional array

In my current code, I am attempting to increase the value of caps by 1 whenever an event with type 10 or 11 is encountered in a loop. However, when running the code, I am encountering an offset 1 error specifically on the line $red_stats[$i]['caps&apo ...

Securing image file paths in PHP

Is there a way to conceal the actual image path in a PHP page or encrypt it somehow so that viewers cannot see the img src? [I have developed a social network where users can choose to share images or not! The images are stored outside of the database.] ...

Looking to access Microsoft Project files (.mpp) on an iPhone or through Objective-C development?

Looking to pull data from a Microsoft Project file (.mpp) and display it on a UITableView. After extensive searching, I have not been able to find a solution for this task. While there are apps on the app store that can do this, I am unable to figure out h ...

Confused between Javascript and PHP? Here's what you should consider!

Looking for a solution to transfer a string from JavaScript, obtained from the content of a div, to PHP in order to create a text file with this information. What would be the most effective approach to accomplish this task? Edit[1]: Using the Post ...

Retrieving data from MySQL through AJAX does not yield any information

I have been following a tutorial from W3 schools on PHP and AJAX database. Majority of the content is working fine, however it seems that there is no data being retrieved from the MySQL database I created called "exercises" in the "exercisedb" database. B ...

Symfony 3.4 is not compatible with installing dotenv via composer

I am currently working on a Symfony 3.4 project and I'm encountering some issues while trying to install the Dotenv component. After running the command composer require symfony/dotenv:^3.4, Composer indicates that there is "Nothing to install update. ...

Using PHP to create a NULL value in a .JSON file

After encountering a NULL value in my .json file when trying to write an array to it, I am puzzled as to why this issue only arises with the 'array_push' line after creating a new file. Interestingly, if there is already a .json file present with ...

preg_match_all is not capturing all the matches

Here is a sample text that requires filtering: 12:00 NAME HTG DAW SDAWERWF 15:00 NUM LEON PARA 20: PEAX SHU MAN POP and I am using the following regular expression for filtering: /([0-9]{2})(.*)([0-9]{2})/ within this code block: preg_match_all ($patter ...

Although the ajax call returned a 404 Not Found error, the functionality of the code still

$(".click").click(function(){ var request = $.ajax({ type: "POST", url: "post.php", data: {file: "123"} }); }); Despite encountering a "404 Not Found" error in Firebug when running this code with the po ...

Looking for the location of the apc.php file?

I've successfully deployed the APC cache on AWS Elastic Beanstalk (confirmed via phpinfo()) How can I verify if APC is functioning properly? Where can I find the location of the apc.php file? Thank you ...

What steps can I take to safeguard my database from potential mySQL injections

I've been researching how to prevent SQL injection in our database, but I haven't found a definitive answer. It seems like using mysql_real_escape_string for MySQL or PDO for other databases are common suggestions. When inserting user input into ...

JQuery organizing and arranging list with drag and drop functionality

Hey there, I've encountered a little dilemma. I've developed a drag and drop list feature in my WordPress plugin that allows users to rearrange categories. For the most part, it's working smoothly... The table is being populated from a MySQ ...

`The Conundrum of Basic HTML Parsing`

Hello, I am currently working on extracting professor names and comments from the ratemyprofessor website by converting each div into plaintext. The following is the structure of the div classes that I am dealing with: <div id="ratingTable"> <div ...

Symfony allows for unique field validation for one-to-many relationships

My Request entity contains multiple Interventions structured as follows: Request.php /** * @ORM\OneToMany(targetEntity=Intervention::class, mappedBy="request") * @Assert\Count(min=1, max=3) * @Assert\Valid ...