/    Sign up×
Community /Pin to ProfileBookmark

Find and Update specific array

I’m looping through a JSON file. I’m looping through this and creating my own array and updating items in my array.

For example imagine I have the follow

TV (2)
Washing Machine (33)
Fridge (23)
TV (2)
Car (4)
TV (2)

As I loop though I’m getting the object ID, 2 for the TV. I’m doing this by saying

`if (in_array($json[“ID”], $myArray”){`

As my array is empty I’m inserting a new row

`$myArray[] = array(‘Object’ => $json[“ID”], ‘Count’ => 1);`

My question is when I get to the next TV and my in_array returns true. How can I get this specific item and update the count by one??

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMar 02.2022 — Probably easier if you use that ID as the $myArray top-level index (assuming those IDs should be unique?).
<i>
</i>if(!isset($myArray[$json['ID']])) {
$myArray[$json['ID']] = array('Object' =&gt; $json["ID"], 'Count' =&gt; 1);
} else {
$myArray[$json['ID']]['count'] += 1;
}
Copy linkTweet thisAlerts:
@NogDogMar 02.2022 — PS: If you take that approach, the Object element becomes redundant, since you could get it from the array key, so you wouldn't really need to include it. If so, and if Count is actually the only field, then you could even get rid of that and simplify the array to just 1 dimension, e.g.:
<i>
</i>$countsById = [
2 =&gt; 3,
33 =&gt; 1,
2 =&gt; 1,
4 =&gt; 1
];

(All depends on what you're actually trying to do with that array and what data you ultimately need in it, so just food for thought at this point.)
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.23,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...