Exploring and sifting through JSON data in PHP

Can someone assist me with parsing and navigating through JSON results using PHP? In the example below, I need to specifically target technology categories.

What I want to achieve is to identify if the category 'analytics' exists in the result, set a true variable, and also record the name of the analytics tool like "Google Analytics".

Here's a snippet of the code:

foreach ($resp['technologies'] as $item) {
    if ($item['categories'][0] === 'analytics') {
        $found = true;
        $analyticsName = $item['name'];
}

This is the JSON data we are dealing with:

[{
    "url": "https://www.websiteexample.co.uk",
    "technologies": [{
      "slug": "google-analytics",
      "name": "Google Analytics",
      "versions": [],
      "trafficRank": 0,
      "categories": [{
          "id": 10,
          "slug": "analytics",
          "name": "Analytics"
        },
        {
          "id": 61,
          "slug": "saas",
          "name": "SaaS"
        }
      ]
    }

Answer №1

Initially, it's important to understand that the variable json represents a string.
If you are dealing with json data, it must be parsed:

$data = json_decode($json, true);

It's crucial to note that if your "json" is presented as an array, it should not be referred to as JSON but rather as an array.


Exploring for Data

To find specific information within the structured data, navigate through the structure until you locate the desired content and then save the relevant details:

$json = <<<'JSON'
[{
    "url": "https://www.examplewebsite.com",
    "technologies": [{
      "slug": "google-analytics",
      "name": "Google Analytics",
      "categories": [
        {"id": 10, "slug": "analytics", "name": "Analytics"},
        {"id": 61, "slug": "saas", "name": "SaaS"}
      ]
    }]
}]
JSON;

$data = json_decode($json, true);

$needle = 'analytics';
$foundTech = null;
$foundCategory = null;
foreach ($data as $resp) {
  foreach ($resp['technologies'] as $tech) {
    foreach ($tech['categories'] as $category) {
      if ($category['slug'] === $needle) {
        $foundTech = $tech;
        $foundCategory = $category;
        break 3;
      }
    }
  }
}
if ($foundCategory) {
  echo $foundTech['name'], PHP_EOL;
  echo $foundCategory['name'], PHP_EOL;
}
Google Analytics
Analytics

If multiple searches within the structure are required, consider establishing maps or indices beforehand for efficiency.

Answer №2

$products['categories'][0] contains an associative array, with statistics located in the tag section.

if ($products['categories'][0]['tag'] == 'statistics') {
    $located = true;
    $statisticIs = $products['name'];
}

You might want to explore all categories, rather than just examining [0].

foreach ($products['categories'] as $category) {
    if ($category['tag'] == 'statistics') {
        $located = true;
        $statisticIs = $products['name'];
        break;
    }
}

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

Invoking a Vue method within a Laravel blade template

In my Laravel project, I have a blade that is loading a Vue component successfully. However, I am facing an issue where calling a method in the Vue component from a select box in the blade is not working as expected. Despite having a method call set up to ...

How to store an imported JSON file in a variable using TypeScript

I am facing a challenge with a JSON file that stores crucial data in the following format { "login": { "email": "Email", "firstName": "First name", "lastName": "Last name", ...

I would like to include the value of the "file_id" variable in the href attribute of an appended HTML element, but it seems

<div id="invite_popup"> </div> $(".invite_button2").click(function(){ var file_id = $(this).data("id"); //alert(file_id); var popup2 ='< ...

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

Retrieve data from two tables in PHP and display the table name

My current PHP code is designed to retrieve data from two different tables in MySQL using the UNION statement. $sql=" SELECT 'ticket_updates' as rowTable, sequence, ticket_seq, notes as displaydata, date ...

Transfer database records to JSON format

I have been working on fetching data from a MySQL server and saving it as JSON. However, I encountered an issue where the date format is lost during the transformation to JSON. Take a look at start & end in both the original data and the output. Esta ...

Since switching to PHP 5.5 from version 3.x, I have noticed that it is attempting to interpret my JavaScript comment within a script tag in a PHP include file

After a long break from working with PHP, I recently encountered an issue with an older website I built using PHP and the include function. The site was functioning perfectly until the web host updated PHP to version 5.5, causing a strange bug where it see ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

"Incorporating a new column into the database through the model and controller in Yii

When working in the Yii MVC framework, I decided to add a new column to my database model using the following code: $success = Yii::app()->ft_website_prod->createCommand()->addColumn('ft_website.users', 'columnname', 'va ...

How to fill out a multi-select dropdown in Laravel

Attempting to populate a multiple select field in Laravel has been giving me some trouble. Here's what I've tried: {{ Form::select('maisons[]', $maisons, $partenaire->maisons->pluck('id'), ['class' => &apos ...

Getting user information using the stored values in an array in PHP and MYSQL

Hey everyone, I successfully added arrays to the database using HTML checkboxes. Now, I am trying to filter students based on their study years and modes from the array but it doesn't seem to be working. Here's what I have tried so far: $StudyYea ...

The functionality of Embedded Jetty's org.eclipse.jetty.util.log.StrErrLog appears to be malfunctioning

My embedded Jetty setup using Jersey Moxy JSON support is working fine with @GET requests, but encountering issues with the single @PUT request I have as it never gets hit. Additionally, the cross-origin filter configured in web.xml doesn't seem to be ...

Using Kotlin on the Android platform, learn how to convert a string into a JSON string

Seeking to convert a string into a JSON string using Gson. My desired outcome is to transform "email" into "{"email" : "$email"}" I have the function: fun serializeUserEmail(email: String): String { return &quo ...

How to extract information from a shared notebook on Evernote using Python

Trying to retrieve data from a shared Evernote notebook, such as this one: Initially attempted using Beautiful Soup: url = 'https://www.evernote.com/pub/missrspink/evernoteexamples#st=p&n=56b67555-158e-4d10-96e2-3b2c57ee372c' r = requests.g ...

Transmit data from an HTML form to PHP using JSON

I am attempting to utilize JavaScript to send POST data. I have the data in an HTML form: <form name="messageact" action=""> <input name="name" type="text" id="username" size="15" /> <input name="massage" type="text" id="usermsg" si ...

"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 ...

Adding a specific key-value pair to every individual object within an array using JMESPath

Looking to transform the data using a JMESPath query where the initial structure is, [ { "key1": true, "key2": true }, { "key1": true, "key2": true } ] into the following format, [ { &q ...

Converting XML data into a properly formatted JSON string

Looking to feed XML into an api endpoint, but first need to convert it to a JSON valid string. Many online parsers convert XML to a JSON object with the same structure as the XML, but that's not what I want. I need the XML converted into a string for ...

Struggling to make $http post requests to PHP using Angular

I am experiencing difficulties in transferring data to my PHP file after decoding Json, resulting in an error. I need assistance in identifying where I have made a mistake. app.js $scope.formPost = function(){ $http.post('sendmail.php' ...

"Encountered a MySQL error while attempting to perform an update

I have a question: Within my database, there are 2 tables: articles: id useid title users id name surname In my view: Author<select name="author" id="author"> <?php foreach ($users as $u): ?> ...