Replace an array inside a multidimensional array if the key exist - php

I am trying to build a form where user inputs a data from a string and the form will get subsets of data through json src based on the input and create a multidimensional array and save it in database. If the input was previously added to database, I dont want it to append in the array again.
Here is how my code looks:
//SET UP the Array
$thisquery_themes[] = array(
strtolower($themename) => array(
"author"=>$data['Author'],
"desc"=>$data['Description'],
"screenshot"=> $screenshot,
"link"=> $data['URI'],
"count"=> 1
)
);
//Get Previously saved data
$existing_themes = get_option('top_themes');
if(!empty($existing_themes)){
foreach ($existing_themes as $group){
foreach(array_keys($group) as $key) {
if($group[strtolower($themename)] == strtolower($themename)){
unset($group[$key][strtolower($themename)]);
}
}
}
$total_themes= array_merge($existing_themes , $thisquery_themes);
update_option('top_themes', $total_themes);
} else {
update_option('top_themes', $thisquery_themes);
}
its not. if the key exist in the array, the data is still being added in the array:
Array (
[0] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[1] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[2] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 1
)
)
[3] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[4] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 1
)
)
But I want it to be like this(Notice how "count" field value added up. let me know if its possible ):
Array (
[0] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 3
)
)
[1] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 2
)
)
Any help would be greatly appreciated. Thanks

Why are you using an array within an array if it's only going to hold one value? Unless that's what's being thrown at you, your structure could easily look like:
Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 3
)
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 2
)
)
Then your world would become a lot easier because you could check to see if the array element exists by using isset($existing_themes[strtolower($themename)]) (as an example.)
If you can't change how you receive $existing_themes, you can reformat the data like this:
$existing_themes_mod = array();
foreach ($existing_themes as $t) {
$existing_themes_mod[key($t)] = reset($t);
}
This should give you enough of a strategy to work with an be able to run an "update" on existing entries instead of an appendage. If you need help writing it, please show me your attempt first.
EDIT - Thanks for pasting your code. You should watch out for all that whitespace by the way... here's a better way to achieve your goal
if (!empty($existing_themes)) {
if (isset($existing_themes[strtolower($themename)])) {
if (isset($existing_themes[strtolower($themename)]['count'])) {
$existing_themes[strtolower($themename)]['count'] = $existing_themes[strtolower($themename)]['count'] + 1;
} else {
$existing_themes[strtolower($themename)]['count'] = 1;
}
$thisquery_themes = array();
}
$total_themes= array_merge($existing_themes , $thisquery_themes);
update_option('top_themes', $total_themes);
} else {
update_option('top_themes', $thisquery_themes);
}
The reason your attempt didn't work is because when you try to change the $value by incrementing it by 1, it doesn't modify the original array. When you use foreach like that, you need to iterate by reference or else you can't modify the value. You're making too much work for yourself!

Related

Getting out the value of a key in multidimentional array in php

In my php query I got this output:
{"projects":[{"id":127,"name":"efrat","status":{"id":10,"name":"development","label":"development"},"description":"","enabled":true,"view_state":{"id":10,"name":"public","label":"public"},"access_level":{"id":90,"name":"administrator","label":"administrator"},"custom_fields":[{"id":1,"name":"Customer email","type":"email","default_value":"","possible_values":"","valid_regexp":"","length_min":0,"length_max":50,"access_level_r":{"id":10,"name":"viewer","label":"viewer"},"access_level_rw":{"id":10,"name":"viewer","label":"viewer"},"display_report":true,"display_update":true,"display_resolved":true,"display_closed":true,"require_report":false,"require_update":false,"require_resolved":false,"require_closed":false}],"versions":[],"categories":[{"id":93,"name":"Monitor","project":{"id":0,"name":null}},{"id":31,"name":"Proactive","project":{"id":0,"name":null}},{"id":30,"name":"Project","project":{"id":0,"name":null}},{"id":29,"name":"Support","project":{"id":0,"name":null}}]}]}
after using 'json_decode' method on it, I get this:
"(
[projects] => Array
(
[0] => Array
(
[id] => 127
[name] => myprojectname
[status] => Array
(
[id] => 10
[name] => development
[label] => development
)
[description] =>
[enabled] => 1
[view_state] => Array
(
[id] => 10
[name] => public
[label] => public
)
[access_level] => Array
(
[id] => 90
[name] => administrator
[label] => administrator
)
[custom_fields] => Array
(
[0] => Array
(
[id] => 1
[name] => Customer email
[type] => email
[default_value] =>
[possible_values] =>
[valid_regexp] =>
[length_min] => 0
[length_max] => 50
[access_level_r] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[access_level_rw] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[display_report] => 1
[display_update] => 1
[display_resolved] => 1
[display_closed] => 1
[require_report] =>
[require_update] =>
[require_resolved] =>
[require_closed] =>
)
)
[versions] => Array
(
)
[categories] => Array
(
[0] => Array
(
[id] => 93
[name] => Monitor
[project] => Array
(
[id] => 0
[name] =>
)
)
[1] => Array
(
[id] => 31
[name] => Proactive
[project] => Array
(
[id] => 0
[name] =>
)
)
[2] => Array
(
[id] => 30
[name] => Project
[project] => Array
(
[id] => 0
[name] =>
)
)
[3] => Array
(
[id] => 29
[name] => Support
[project] => Array
(
[id] => 0
[name] =>
)
)
)
)
)
)"
In my PHP, how can I release the "name" object value (the result should be 'myprojectname') from this array? I've tried many foreach loops that got me nowhere.
Thank you,
It looks like you have one object, that when decoded actually only has one array item. So, in your case, ‘myprojectname’ may simply be “$projects[0][‘name’]”
If many array items, you could
foreach ($projects as $project) {
echo $project[‘name’];
}
EDIT: I took object provided and json_decoded it myself, it doesn't match the json_decoded item presented by OP -- the first image shows the code to var_dump 'name' OP desired, part of the code also below:
$decoded = json_decode($obj);
$projects = $decoded->projects;
$name = $projects[0]->name;
Your 'projects' contains an array ("projects":[{"id":127, ... }]). I assume that the 'projects'-array might contain multiple 'project'-objects like this?
{
"projects":
[
{
"id":127,
"name":"my-project"
},
{
"id":128,
"name":"my-other-project"
}
]
}
In that case you need the arrow notation to access the name property, for example:
foreach ($projects as $project_object) {
foreach ($project_object as $project) {
echo $project->name . '<br/>';
}
}
EDIT:
I took a minimal code example of the OP and got the expected result:
Can you add more details in your code snippets in your original question or provide us with a working example of your code?
There are some online PHP sandboxes that can help you with this. For example: I stripped out all code that does not seem related to your question and got the result you are looking for in two different ways:
http://sandbox.onlinephpfunctions.com/code/009c53671fd9545e4fcecfe4b0328974381ee2ce
It is also a good idea to sum up all the foreach loops that you already tried, so we can see if you were nearly there with your own solution. This way we can understand your question better and it prevents us from offering solutions that you already used.

PHP efficiently accessing values in a JSON array on different levels

Working on a personal project that will pull results from an API with full details of each pokemon.
So far I got the contents of the URL and returned the results into a JSON array format.
At the moment I am stuck on trying to retrieve results for[stats] inside from the array in an efficient manner.
private function getGenOnePokemon()
{
// the url of the api
$url = $this->baseUrl;
//get the contents of $url var and decode it into a json array
$json = file_get_contents($url , true);
$pokemon = json_decode($json, true, JSON_UNESCAPED_UNICODE);
// array output of pokemon
echo '<pre> ';
print_r($pokemon);
echo'</pre>';
//echo out value as speed
foreach($pokemon['results'][0] as $happy)
{
echo $happy['name'] . '<br />';
}
// echo base_stat value for speed with value of 90
echo $pokemon['stats'][0]['base_stat'];
}
However I do not seem to get anywhere much printing values/keys as I need to add something else to have full access to the values?
Would prefer not to directly access results, like I am doing with base_stat as plan on using this logic to pass into HTML View layer later.
Example of print_r dump (not full dump as really long) Full example: https://pokeapi.co/api/v2/pokemon/pikachu
Array
(
[forms] => Array
(
[0] => Array
(
[url] => https://pokeapi.co/api/v2/pokemon-form/25/
[name] => pikachu
)
)
[abilities] => Array
(
[0] => Array
(
[slot] => 3
[is_hidden] => 1
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/31/
[name] => lightning-rod
)
)
[1] => Array
(
[slot] => 1
[is_hidden] =>
[ability] => Array
(
[url] => https://pokeapi.co/api/v2/ability/9/
[name] => static
)
)
)
[stats] => Array
(
[0] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/6/
[name] => speed
)
[effort] => 2
[base_stat] => 90
)
[1] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/5/
[name] => special-defense
)
[effort] => 0
[base_stat] => 50
)
[2] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/4/
[name] => special-attack
)
[effort] => 0
[base_stat] => 50
)
[3] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/3/
[name] => defense
)
[effort] => 0
[base_stat] => 40
)
[4] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/2/
[name] => attack
)
[effort] => 0
[base_stat] => 55
)
[5] => Array
(
[stat] => Array
(
[url] => https://pokeapi.co/api/v2/stat/1/
[name] => hp
)
[effort] => 0
[base_stat] => 35
)
)
Any advice on how to access the data using foreach or other tips greatly appreciated. Thank you!
PHP has a specific function designed to target columnar data from arrays. It is called array_column()
If you want to isolate all of the name elements inside the forms subarray, use this:
$names=array_column($pokemon['forms'],'name');
If you want to isolate all of the base_stat elements inside of the stats subarray, use this:
$base_stats=array_column($pokemon['stats'],'base_stat');
Now you will have $names and $base_stats which are single-dimensional arrays by which you can perform additional processes or return from the function. Clean, intuitive, and simple.
Your $pokemon array doesn't contain a results field. There's only an forms field. So you should iterate over forms to print the names of the forms.
foreach($pokemon['forms'] as $happy) {
echo $happy['name'] . '<br />';
}
You could do the same thing with the stats
foreach($pokemon['stats'] as $stat) {
$base_stat = $stat['base_stat'];
// ...
}

Multisorting a nested array in php

I've got a bunch of content pulled out of several databases and compiled into a nested array like this:
Array
(
[0] => Array
(
[id] => 3
[published] => 1433940002
[content] => This is some content
)
[1] => Array
(
[id] => 52
[published] => 1433940001
[content] => This is some more content
)
[2] => Array
(
[id] => 16
[published] => 1433940003
[content] => This is some more content
)
)
Since I cannot sort the content whilst it is retrieved (because it is done using several queries from as many databases) I want to dig down a level into the array and sort by the "published" date whilst maintaining the depth of the array so I end up with...
Array
(
[0] => Array
(
[id] => 52
[published] => 1433940001
[content] => This is some more content
)
[1] => Array
(
[id] => 3
[published] => 1433940002
[content] => This is some content
)
[2] => Array
(
[id] => 16
[published] => 1433940003
[content] => This is some more content
)
)
I'm pretty sure array_multisort() is the way to go but I can't think where to start! Could somebody be so kind as to give me a pointer?
Thanks to #Rizier123's policing of my question I figured it out myself. For anyone else finding this thread here's my solution using the example array I supplied above.
//-- get disorganised content from databases here
usort($array, "publishcmp");
//-- output organised content here
function publishcmp($a , $b){
if ($a['published'] == $b['published']) {
return 0;
}
return ($a['published'] < $b['published']) ? -1 : 1;
}
Pretty much taken verbatim from php.net

new array be joining 2 arrays at random

Dear stackoverflow members,
I want to join 2 arrays in random as mentioned below, i tried different methods but i was not able to produce the result that i exactly wanted.
I have 2 arrays which looks like this. Lets call this names.
Array
(
[bill] => Array
(
)
[steve] => Array
(
)
[Ritchie] => Array
(
)
)
now these names are generated from another function, it's output looks something like this.
Array
(
[1] => Array
(
[email] => info#bill.com
[name] => bill
[web] => http://bill.com
)
[2] => Array
(
[email] => rich#steve.com
[name] => steve
[web] => http://steve.com
)
[3] => Array
(
[email] => god#linux.com
[name] => Ritchie
[web] => http://linux.com
)
[4] => Array
(
[email] => dummy#dummy.com
[name] => Ritchie
[web] => http://linux.com
)
)
and the 2nd array, lets call it countries.
Array
(
[0] => USA
[1] => UK
[2] => Netherlands
[3] => Australia
[4] => Germany
)
Now here is the exact problem. i want the 1st array names and the 2nd array countries to be joined and form another associative array in random order. But please note that the function which returns the name array returns the key : Ritchie twice, it has 2 occurrences. So the final array should be something like this.
Array
(
[Ritchie] => Array
(
[0] => USA,
[1] => Germany
)
[bill] => Array
(
[0] => Netherlands
)
[steve] => Array
(
[0] => UK
)
)
Since the key Ritchie has 2 occurrences, 2 unique values from the country array should be added. The number of keys or occurrences in names and the keys in countries will always be the same. If their is anything unclear, let me know i'll clear it out.
I did heavy research on the internet and stackoverflow and i was only able to come up with this. The current solution i have is this. Please be kind to help me to improve the current lines of code to suit my need or may be this might not be elegant, if so, please be kind to suggest a better solution.
$jumble = array();
foreach ($names as $name) {
$jumble[$name] = $countries[array_rand($countries)];
}
Thank you.
Try this code:
shuffle($countries);
$n = count($countries); $i = 0;
$jumble = array();
foreach ($names as $name) {
if (!isset($jumble[$name])) $jumble[$name] = array();
$jumble[$name][] = $countries[$i++ % $n];
}
Demo

Sort array according to the search string occurence php

I want to sort two dimensional array according to the occurrence of the search string in php. i tried to fetch data according to the relevance of search string . i come across match and against but it will work on the MYISAM but my table is in innodb. so plan to sort the array using any sort function but i cant find out anything.
my search pressure tes string array
Array
(
[0] => pressure
[1] => tes
)
My output array which matches the above string with title is
Array
(
[0] => Array
(
[title] => tests.doc
[link] => http://localhost/test.doc
[snippet] =>
)
[1] => Array
(
[title] => Pressure Testing Your Company
[link] => http://localhost/Pressure_Testing_Your_Companys.pdf
[snippet] => Questions used by the CFO against dimensions critical to success
)
[2] => Array
(
[title] => pressure.doc
[link] => http://localhost/pressure.doc
[snippet] => Templates for services
)
)
In the above array the most relevant array[1] then array[2] and then array[0] should be in this order. i want to sort this array accordingly. my output should be like below:
Array
(
[0] => Array
(
[title] => Pressure Testing Your Company
[link] => http://localhost/Pressure_Testing_Your_Companys.pdf
[snippet] => Questions used by the CFO against dimensions critical to success
)
[1] => Array
(
[title] => pressure.doc
[link] => http://localhost/pressure.doc
[snippet] => Templates for services
)
[2] => Array
(
[title] => tests.doc
[link] => http://localhost/test.doc
[snippet] =>
)
)
please help me!!!!
Look at the example #3, I think that's what you want.
http://php.net/manual/en/function.array-multisort.php
Just tested this, it seems to be working :
$titles = array();
foreach ( $array as $key => $value )
{
$titles[ $key ] = $value['title'];
}
array_multisort( $titles, SORT_ASC , $array );
I would highly recommend to sort your results in your MySQL query, that would be much better performance wise.

Categories