Traversing a multi-dimensional array with changing keys in PHP

Recently delving back into the world of basic PHP, I encountered a roadblock while dealing with a JSON response. I successfully converted the response into an Array, but it seems to be multi-dimensional. The challenge lies in isolating and extracting values from an Array where the key constantly changes.

Below is the structure of the array, and my goal is to extract the keyword (e.g., "garmin gps systems", "satmap gps systems"), Google position, and the associated URL.


    Array
    (
        [api] => cognitiveSEO API
        [data] => Array
            (
                [status] => success
                [data] => Array
                    (
                        [2015-07-16] => Array
                            (
                                [garmin gps systems] => Array
                                    (
                                        [locale] => en-uk
                                        [google] => Array
                                            (
                                                [position] => 
                                                [url] => 
                                            )

                                        [bing] => Array
                                            (
                                                [position] => 8
                                                [url] => http://www.aboveandbeyond.co.uk/gps-and-navigation/gps-systems/garmin
                                            )

                                        [yahoo] => Array
                                            (
                                                [position] => 8
                                                [url] => http://www.aboveandbeyond.co.uk/gps-and-navigation/gps-systems/garmin
                                            )

                                    )
                                    
                                [satmap gps systems] => Array
                                    (
                                        [locale] => en-uk
                                        [google] => Array
                                            (
                                                [position] => 25
                                                [url] => http://www.aboveandbeyond.co.uk/gps-and-navigation/satmap
                                            )

                                        [bing] => Array
                                            (
                                                [position] => 4
                                                [url] => http://www.aboveandbeyond.co.uk/gps-and-navigation/gps-systems/satmap
                                            )

                                        [yahoo] => Array
                                            (
                                                [position] => 4
                                                [url] => http://www.aboveandbeyond.co.uk/gps-and-navigation/gps-systems/satmap
                                            )

                                    )

In my attempt to display these values in a table using a foreach loop, I need assistance on how to reference the changing keyword value within the array;


    foreach($data as $rows) {
        echo '';
        echo ''.$rows['??'].'';
        echo ''.$rows['position'].'';
        echo ''.$rows['url'].'';
    }

Your help would be greatly appreciated, as I have searched extensively but haven't found a solution yet.

Answer №1

To handle the array, I would store it in the $arr variable and then loop through it to process multiple dates as shown below:

foreach ($arr['data']['data'] as $date => $data) {
    foreach ($data as $gps_key => $gps_data) {
        $final[$date][] = array(
            "key" => $gps_key,
            "position" => $gps_data['google']['position'],
            "url" => $gps_data['google']['url']
        );
    }
}

var_dump($final);

The output will be:

Array
(
    [2015-07-16] => Array
        (
            [0] => Array
                (
                    [key] => garmin gps systems
                    [position] => 
                    [url] => 
                )

            [1] => Array
                (
                    [key] => satmap gps systems
                    [position] => 
                    [url] => 
                )

        )

)

Answer №2

Despite alterations to the key values, you can continue to loop through by accessing $array[0], $array[1], and so on.

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

Instructions for including a script and stylesheet exclusively on a single page of a website

I need to incorporate these two lines onto a single page of my website: <script src="//cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.js"></script> As well as <link href="//cdnjs.cloudflare.com/ajax/libs/OwlCa ...

How to eliminate an element from numerous arrays using jQuery?

Is it possible to use jq to remove all instances of a specific name from arrays within the input data? For example, removing "Name1" from the following: { "Category1": [ { "name": "Name1", "desc": "Desc1" }, { "name": "Name ...

Error: You have encountered an Uncaught SyntaxError due to an Unexpected token being found

When I make an AJAX call using jQuery, it's causing an error on a real server but works fine on LAMP and WAMP. Here is the code snippet for the AJAX call: function wordAnalysis() { $("#spinner").show(); removeTopics(); $.ajax({ ...

The occurrence of Simplejson decoding error arises solely during the execution of more than two iterations

I'm using the names module in conjunction with a wrapper for temp-mail.org (https://github.com/saippuakauppias/temp-mail) as part of my project that involves generating temporary email addresses. The code I have provided below is functioning properly ...

Show as EXPIRED if the number of days is negative

I have a task that I want to accomplish: if the number of days is less than 0 (negative), it should display as "EXPIRED." How can I modify my code to show "expired" instead of displaying -1 when the number of days is negative? You can view the output her ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

Issue with PHP and Jquery contact form causing blank emails to be sent

I've been on the hunt for a solution, but nothing seems to work from other topics I've seen. So, I'm reaching out with my query now. Apologies if it overlaps with another question. Below is the html markup within <head></head> ...

Adding elements to a two-dimensional array using AngularJS

How can I assign the value of an input to tasks.name and automatically set status: false when adding a new item to the $scope.tasks array? HTML <input type="text" ng-model="typeTask"> <button ng-click="updateTasks()">Add task</button> ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

Discover how to extract JSON data from a webpage even when the response is "None"

I need to retrieve data maps from their API, which are in JSON format. This is the code I have written: r = requests.get(url) if r.ok: soup = BeautifulSoup(r.content, 'lxml') soup.status_code j = json.loads(str(soup)) However, an e ...

Strategies for thorough module testing in my PHP application using PHPUnit and Zend Framework 2

I have successfully tested my application module and another module separately. However, I would like to run all tests (both for the application module and the other module) together in order to generate a clover report for Jenkins. What steps should I tak ...

What is the process for dynamically assigning a color picker hex value as HTML attributes in PHP?

Is it possible to create a color picker that allows the user to select a hex value and then automatically apply it as an attribute in an HTML tag, like shown below? <p style="background-color: #FCF8C0;">TEXT GOES HERE</p> In the code example ...

Steps to Show New Blog Entries on WordPress Homepage Only After Clicking a Link

When a specific tab is clicked on the WordPress blog home page, the following process should be initiated. The content should be displayed using AJAX for a smoother user experience. For instance, in the blog homepage, there are three tabs titled "They Li ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

Is it possible to increase the thumbnail size through the YouTube API?

I am currently leveraging the YouTube API to fetch thumbnails. After inspecting, I have found that all thumbnails are sized at 90 × 120 pixels. Is there a method to retrieve them in larger dimensions? My approach involves using PHP 5.3 and SimpleX ...

PHP: Utilizing Interfaces as Function Parameters

Can I pass interfaces as parameters in PHP class methods like I can in .NET? Here's my scenario: I have a class that handles the main system functionality, but now I want to integrate a separate Notification system. I want to keep the notification sy ...

Using Ext JS to send an AJAX request with a JSON object to an ASP.NET MVC web application

Currently, I am attempting to transmit a json object (extjs client) to an asp.net server-side application: Here is the sample request with logic intact: var orderData = []; for (i = 0; i < checkedList.length; i++) { orderData.push ...

Passing JSON information from a website to a Node.js server

<script type="text/javascript" src="data.json"></script> var mydata = JSON.parse(data); data = '[{"yer" : "Besiktas", "lat" : "41.044161", "lng" : "29.001056"},{"yer" : "Eminönü", "lat" : "41.017513", "lng" : "28.970939"},{"yer" : "Zeyt ...

What is the method for retrieving media:* namespace values from an XML file?

I am currently working on extracting specific information from an XML RSS feed retrieved from Zazzle's API. The goal is to extract the title, price, thumbnail, and link (guid) for each item in the feed and store this data in an array. This array will ...

Looking for a JavaScript function that can utilize AJAX to execute PHP code and display the PHP output on the webpage

I've been trying to use JavaScript to execute some PHP code and then display the results on the page. I came across a piece of code that achieves this using ajax and by placing the PHP code in an external file. However, the code I found seems to show ...