ARTICLE AD BOX
I am working with a structured JSON dataset where each ingredient contains relational metadata such as:
reacts_with
affected_by
compatible_with
A simplified structure is like this:
{ "category": "surfactants", "ingredients": [ { "name": "sodium stearate", "reacts_with": ["calcium", "magnesium"], "affected_by": ["hard_water"], "compatible_with": ["nonionic_surfactants"] } ] }The full dataset (for reference): https://cleanformulation.com/data/ingredients-dataset.json
I am trying to find:
all ingredients affected by "hard_water" all ingredients that react with "calcium"I am currently using a simple PHP loop like this:
<?php $data = json_decode(file_get_contents('ingredients-dataset.json'), true); $result = []; foreach ($data as $category) { foreach ($category['ingredients'] as $ingredient) { if (in_array('hard_water', $ingredient['affected_by'])) { $result[] = $ingredient['name']; } } } print_r($result); ?>This works for small data, but becomes inefficient as the dataset grows, I have to loop through all categories and ingredients every time
It feels redundant when querying multiple relationships
Is there a better way in PHP to query these relationships without full iteration each time?
9,19662 gold badges208 silver badges222 bronze badges
New contributor
Parvaiz Ahmad is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
3
