Determine the number of keys within a JSON array

The issue lies not in the counting itself, but rather in setting the key-value pairs. Here's the snippet of code:

<?php
$jsonPacks = '{
    "pack": [
        {
            "container": 50,
            "layout": [
                {
                    "id": 4054,
                    "stacksize": 1
                }
            ]
        },
        ...
    ]
}';
function _countItemsByContainer($containerId, $arrayPack) {
    $obj = [];
    ...
}
$arrayPack = json_decode($jsonPacks, true);
$totalCartonizations = count($arrayPack['pack']);
$countItemsByContainer = [];
for ($k = 0;$k < $totalCartonizations;$k++){
    $countItemsByContainer[] = _countItemsByContainer($k, $arrayPack);
}
print_r(json_encode($countItemsByContainer));
?>

This is the output from the code:

[
    {
        "4054": 1
    },
    ...
]

Which is accurate. The count reflects the number of each id in the 6 packs.

The desired JSON structure is as follows:

{
    "pack": [
        {
            "item": [
                {
                    "id": 4054,
                    "total": 1
                },
            ]
        },
        ...
    ]
}

Your assistance would be highly appreciated.

Thank you.

Answer №1

Here is the provided solution:

function _countItemsByContainer($containerId, $arrayPacks) {
    for ($j = 0;$j < count($arrayPacks['pack']);$j++) {
        if ($j == $containerId) {
            $allItems = [];
            for ($k = 0; $k < count($arrayPacks['pack'][$j]['layout']); $k++) {
                if (in_array($arrayPacks['pack'][$j]['layout'][$k]['id'], $allItems)) {
                    $key = array_search($arrayPacks['pack'][$j]['layout'][$k]['id'], array_column($obj['item'], 'id'));
                    $obj['item'][$key]['total']++;
                } else {
                    $obj['item'][] = ['id' => $arrayPacks['pack'][$j]['layout'][$k]['id'], 'total' => 1];
                    $allItems[] = $arrayPacks['pack'][$j]['layout'][$k]['id'];
                }                
            }
        }
    }
    return $obj;
}
$arrayPacks = json_decode($jsonPacks, true);
$totalPacks = count($arrayPacks['pack']);
$countItemsByContainer = [];
for ($k = 0; $k < $totalPacks; $k++){
    $countItemsByContainer['pack'][] = _countItemsByContainer($k, $arrayPacks);
}
echo '<pre>';
echo json_encode($countItemsByContainer, JSON_PRETTY_PRINT);
echo '</pre>';

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

Firefoxx effortlessly glides divs across the screen as if they were images

Below is the HTML, CSS, and JavaScript code all in one document for testing: <style type="text/css"> #slider_container { width: 200px; height: 30px; background-color: red; display:block; } #slider { width: 20px; height: 30px ...

JavaScript malfunctioning on Chrome

Displayed on the page is a table that lists user details. When the Edit Button is clicked, it allows for the row to be edited. The code provided below works in IE but does not show any response in Chrome. I am looking to make the site compatible with bot ...

Learn how to dynamically populate a select2 dropdown with values retrieved from a database using JavaScript or jQuery

I am currently working on an edit form where I need to retrieve data from a MySql database using Ajax. The form includes two select2 dropdowns and I want the fetched data to be displayed inside those dropdowns. For example: Let's say I have created a ...

Generate an inclusive list featuring li elements with intricately detailed content within each

Currently, I am in the process of developing a web component and here is my code snippet: <ul class="list-with-arrow${this.inverse ? '--inverse' : ''}"> ${this.listData.map((item, index) => { ...

Is it possible to create classes on the fly as they are being used?

I am currently developing a service that pulls data from an API over HTTP, provided by another team within my organization. The JSON response body structure returned by their API can be illustrated as follows: "SomeObject": { "SomeInnerObject": { ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

What is the process for deciphering a JSON string?

I have run into an issue while working on a project that involves receiving data in JSON string format from Android or iOS applications. I am using json_decode to decode the data, however, I am not getting any array as expected. Both iOS and Android make ...

Leveraging a specific section of an HTML5 CSS3 Bootstrap template in a separate template

As I create my website using a combination of free templates, I often find myself needing to merge elements from different designs. One specific example is wanting to incorporate the "Client Logo Slider" component from template 2 into my original template. ...

The javascript function "Scroll to the element" is not functioning properly on my website. Perhaps using JQuery will resolve the issue

I used this bootstrap template to create my website. Everything worked perfectly except for the "scroll to the element script". I kept encountering the following error: Uncaught Error: Syntax error, unrecognized expression: [href=#],[data-toggle],[data-tar ...

Is there a way to selectively import specific functions from a file in NextJs/React rather than importing the entire file?

Imagine this scenario: we have two files, let's call them File A - export const a = () => {} export const b = () => {} Now, consider importing this into File B - import { a } from 'path' When I tried running npm run analyze, it showe ...

Using Three.js : THREE.VTKLoader() to assign an ID for an event

I have been attempting to load multiple .vtk files using a for loop in the following manner: for (var i = 0; i < vtkFilesArray.length; i++) { var loader = new THREE.VTKLoader(); loader.load( i+".vtk", function ( geometry ) { console.lo ...

React.js - state variable becomes undefined upon uploading app to Amplify

I am encountering a perplexing error and am struggling to determine the root cause. To provide a brief overview, I have a dialog containing a jsonschema form along with an image that is uploaded to an input and saved in b64 format within a state variable c ...

Is it possible to use Javascript to query the neo4j database?

After creating a geohash neo4j database for NYC Taxi data, the next step is to visualize it on a map. I decided to use Leaflet as a JavaScript library. Using static data, I was able to plot geohash data in Leaflet: https://i.sstatic.net/AtQKZ.jpg Now, my ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

What might be causing my lightbox image to fail to load when I click on it?

Whenever I click on the image, the lightbox loads but the actual image fails to load, leaving a blank white box instead. Despite following a tutorial on YouTube that showed me how to create a lightbox step by step, I can't figure out what went wrong. ...

RangeError: The React application has surpassed the maximum stack size limit, causing an error to be thrown

Hey there, I could use a hand. I'm fairly new to React and attempting to develop an application for managing contacts by adding them to Local Storage and deleting them. Below is the code snippet from my App.js file: import React, {useState, useEffect} ...

Modification of a CSS element

The CSS I am working with looks like this: .cls .imageX { float:left; } .cls .imageY { float:right; } It is currently being used on a page in this way: <div class="cls"> <a href="" class="imageX"><img src="left.png"/></a> &l ...

Transforming a tabular dataset into hierarchical JSON structure

import pandas as pd import numpy as np arrays = [ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"], ["one", "two", "one", "tw ...

Filtering elements using two dropdown lists

In my list, each li element has data-name and data-body attributes. I want to display only the li elements that match the selected values. The first select option is for selecting the car name, while the second select option is for selecting the car body. ...

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...