PHP match values between 2 arrays not same key - php

I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.
I have 2 array like below:
BigArray
Array
(
[0] => Array
(
[id] => 1
[category_name] => Accountancy
[category_name_vi] => Kế toán
[category_id] => 1
)
[1] => Array
(
[id] => 2
[category_name] => Armed forces
[category_name_vi] => Quân đội
[category_id] => 2
)
[2] => Array
(
[id] => 3
[category_name] => Admin & Secretarial
[category_name_vi] => Thư ký & Hành chính
[category_id] => 3
)
[3] => Array
(
[id] => 4
[category_name] => Banking & Finance
[category_name_vi] => Tài chính & Ngân hàng
[category_id] => 4
)
)
and SmallArray:
Array
(
[0] => Array
(
[id] => 7
[category_id] => 2
[jobseeker_id] => 1
)
[1] => Array
(
[id] => 8
[category_id] => 3
[jobseeker_id] => 1
)
)
Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:
Matched array:
Array
(
[0] => Array
(
[2] => Armed forces
)
[1] => Array
(
[3] => Admin & Secretarial
)
)
So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(
Thanks

This should do that:
foreach ($smallArray as $smallKey => $smallElement) {
foreach ($bigArray as $bigKey => $bigElement) {
if ($bigElement['id'] == $smallElement['category_id']) {
$smallArray[$smallKey] = array(
$bigElement['id'] => $bigElement['category_name'],
);
break; // for performance and no extra looping
}
}
}
After these loops, you have what you want in $smallArray.

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.

Echo arrays in foreach loop codeigniter

I've been using codeigniter for years but there's a really big gap in between so i always find myself in situations where i forgot how to do things and its almost midnight here so my brain isn't working fast. Can someone show me how to echo the array i have and explain to me how they are processed in the foreach loops?
I have this code in my model to take the rows in 2 tables.
public function tag_genre(){
$result['tag'] = $this->db->get('tags')->result_array();
$result['genre'] = $this->db->get('genre')->result_array();
return $result;
}
And I have this in my controller
public function view_publish_story(){
$data = array('tag_genre' => $this->story_model->tag_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
I used print_r in my view and this is the result. Seeing this just confuses me more. It's been atleast 2 years since i even dealt with foreach loops.
Array ( [tag] => Array ( [0] => Array ( [tag_id] => 1 [tag_name] =>
LitRPG ) [1] => Array ( [tag_id] => 2 [tag_name] => Virtual Reality )
[2] => Array ( [tag_id] => 3 [tag_name] => Cyberpunk ) [3] => Array (
[tag_id] => 4 [tag_name] => Reincarnation ) [4] => Array ( [tag_id] =>
5 [tag_name] => Summoned Hero ) [5] => Array ( [tag_id] => 6
[tag_name] => Martial Arts ) [6] => Array ( [tag_id] => 7 [tag_name]
=> Slice of Life ) [7] => Array ( [tag_id] => 8 [tag_name] => Overpowered ) [8] => Array ( [tag_id] => 9 [tag_name] => Non-Human )
[9] => Array ( [tag_id] => 10 [tag_name] => Anti-hero ) ) [genre] =>
Array ( [0] => Array ( [genre_id] => 1 [genre_name] => action ) [1] =>
Array ( [genre_id] => 2 [genre_name] => adventure ) [2] => Array (
[genre_id] => 3 [genre_name] => comedy ) [3] => Array ( [genre_id] =>
4 [genre_name] => Drama ) [4] => Array ( [genre_id] => 5 [genre_name]
=> Fantasy ) [5] => Array ( [genre_id] => 6 [genre_name] => Historical ) [6] => Array ( [genre_id] => 7 [genre_name] => Horror ) [7] => Array
( [genre_id] => 8 [genre_name] => Psychological ) [8] => Array (
[genre_id] => 9 [genre_name] => Romance ) [9] => Array ( [genre_id] =>
10 [genre_name] => Sci-fi ) [10] => Array ( [genre_id] => 11
[genre_name] => Mystery ) [11] => Array ( [genre_id] => 12
[genre_name] => Tragedy ) [12] => Array ( [genre_id] => 13
[genre_name] => Short Story ) [13] => Array ( [genre_id] => 14
[genre_name] => Satire ) ) )
I've been looking at various questions regarding arrays from assoc to multidimensional and other stuff. Then i finally visited php manual for foreach loop and i finally was able to echo the array. The problem now is that although it echoes my array it also has an error for each, i can probably fix the error part by declaring it as a defined variable. My question is, is there any other better way? or any improvement on how i made my array to make it cleaner or easier to print?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo $values['tag_name'];
}
}
UPDATE: i changed the way i made the array.
This is now my model:
public function get_tags(){
$query = $this->db->get('tags')->result_array();
foreach($query as $row){
$result[$row['tag_id']] = $row['tag_name'];}
return $result;
}
public function get_genre(){
$query = $this->db->get('genre')->result_array();
foreach($query as $row){
$result[$row['genre_id']] = $row['genre_name'];}
return $result;
}
and my controller:
public function view_publish_story(){
$data = array('tag' => $this->story_model->get_tags(), 'genre' => $this->story_model->get_genre(), 'title' => "New Story");
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/storypublish',$data);
$this->load->view('template/footer');
}
and in my view:
<tr>
<div class="form-group">
<td><label for="genre">Genre</label></td>
<?php
foreach($genre as $genre_id => $genre_name){
echo "<td><label class='checkbox-inline'><input type='checkbox' value=''>".$genre_name."</label><td>";
}
?>
</div>
</tr>
My problem now is that, how do i fit all these into my table? I just ruined my table right now since i echoed them all in a single line. How do i do it so that it is printed in 3 columns?
foreach($tag_genre as $key => $value){
foreach($value as $values){
echo '<pre>';
echo $values['tag_name'];
}
}
this will format your array in a way you can read it and understand it.

array_reduce to use dynamic variables pass in second function

I have below $test array
Array
(
[0] => Array
(
[quantity] => 3
[stock_id] => _PHONE
)
[1] => Array
(
[quantity] => 3
[stock_id] => 102
)
[2] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[3] => Array
(
[quantity] => 3
[stock_id] => 102
)
[4] => Array
(
[quantity] => 4
[stock_id] => _PHONE
)
[5] => Array
(
[quantity] => 6
[stock_id] => _PHONE
)
[6] => Array
(
[quantity] => 2
[stock_id] => 102
)
)
and to sum same stock_id keys to one, i use below functions:
function sum($array, $key){
isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;
return $array;
};
//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum");
and the result went well like below:
$sum_same_stock_id:
Array
(
[_PHONE] => Array
(
[quantity] => 17
[stock_id] => _PHONE
)
[102] => Array
(
[quantity] => 8
[stock_id] => 102
)
)
So the question here is, I wanted to pass an dynamic keys values not just fixed values stock_id & quantity in sum function above. Have tried variety ways but still can't figured out the way. And can we put those functions into class as well?
Any advise is appreciated!
Maybe you can use the "use" function for the callback?
See https://www.php.net/manual/en/functions.anonymous.php

Multidimensional array - duplicate of values through iterations

I have started working with Magento, and I'm trying to get all custom options associated with a given product.
I've found a solution to that, however, I ran into issues.
My PHP-code:
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
It sure do return the correct information. Atleast in the first iteration:
[2] => Array
(
[id] => 2
[type] => drop_down
[title] => Custom option 1
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
)
)
However, during the second iteration (and perhaps even the third and forth and so on), I'm having duplicates of the values. In the second iteration, I'm getting the same values as i got in the first iteration PLUS the correct values for the second iteration:
[1] => Array
(
[id] => 1
[type] => drop_down
[title] => Custom option 2
[values] => Array
(
[4] => Array
(
[option_type_id] => 4
[option_id] => 2
[title] => Flaphack 1
)
[5] => Array
(
[option_type_id] => 5
[option_id] => 2
[title] => Flaphack 2
)
[6] => Array
(
[option_type_id] => 6
[option_id] => 2
[title] => Flaphack 3
)
[1] => Array
(
[option_type_id] => 1
[option_id] => 1
[title] => Flaphack 1.1
)
[2] => Array
(
[option_type_id] => 2
[option_id] => 1
[title] => Flaphack 1.2
)
[3] => Array
(
[option_type_id] => 3
[option_id] => 1
[title] => Flaphack 1.3
)
)
)
Do you guys have any idea what's going on? Would be greatly appriciated.
Best,
Nikolaj
Try this code,
foreach ($_product->getOptions() as $optionInfo) :
$values = $optionInfo->getValues();
$valuesArray = array(); // added line
foreach ($values as $values) :
$valuesArray[$values['option_type_id']] = array("option_type_id" => $values['option_type_id'], "option_id" => $values['option_id'], "title" => $values['title']);
endforeach;
$option = array("id" => $optionInfo->getId(), "type" => $optionInfo->getType(), "title" => $optionInfo->getTitle(), "values" => $valuesArray);
$options[$optionInfo->getId()]= $option;
endforeach;
The $valuesArray is getting values in each iteration and you never cleared it. So when the outer foreach gets into second loop the $valuesArray gets values in incremental fashion. If you clear $valuesArray in each iteration of outer foreach you will get what you wanted.

PhP - Search massive array for value, return parent key.

Q: How to Search Massive Multi-Dimensional Array for Single Value, and Return Parent Array?
I have this massive json that represents all of the achievements in WoW.
http://us.battle.net/api/wow/data/character/achievements
I converted it into an array using json_decode. This then leaves me with a very massive array that I need to search all of its levels until I find a specific value, I then need to return the parent array of that value.
ex:
This is one small part of the decoded array.
[0] => Array
(
[id] => 7385
[title] => Pub Crawl
[points] => 10
[description] => Complete the Brewmaster scenario achievements listed below.
[reward] => Reward: Honorary Brewmaster Keg
[rewardItems] => Array
(
[0] => Array
(
[id] => 87528
[name] => Honorary Brewmaster Keg
[icon] => inv_holiday_brewfestbuff_01
[quality] => 3
[itemLevel] => 90
[tooltipParams] => Array
(
)
[stats] => Array
(
)
[armor] => 0
)
)
[icon] => inv_misc_archaeology_vrykuldrinkinghorn
[criteria] => Array
(
[0] => Array
(
[id] => 20680
[description] => Spell No Evil
[orderIndex] => 0
[max] => 1
)
[1] => Array
(
[id] => 20681
[description] => Yaungolian Barbecue
[orderIndex] => 1
[max] => 1
)
[2] => Array
(
[id] => 20682
[description] => Binan Village All-Star
[orderIndex] => 2
[max] => 1
)
[3] => Array
(
[id] => 20683
[description] => The Keg Runner
[orderIndex] => 3
[max] => 1
)
[4] => Array
(
[id] => 20684
[description] => Monkey in the Middle
[orderIndex] => 4
[max] => 1
)
[5] => Array
(
[id] => 20685
[description] => Monkey See, Monkey Kill
[orderIndex] => 5
[max] => 1
)
[6] => Array
(
[id] => 20686
[description] => Don't Shake the Keg
[orderIndex] => 6
[max] => 1
)
[7] => Array
(
[id] => 20687
[description] => Party of Six
[orderIndex] => 7
[max] => 1
)
[8] => Array
(
[id] => 20688
[description] => The Perfect Pour
[orderIndex] => 8
[max] => 1
)
[9] => Array
( re
[id] => 20689
[description] => Save it for Later
[orderIndex] => 9
[max] => 1
)
[10] => Array
(
[id] => 20690
[description] => Perfect Delivery
[orderIndex] => 10
[max] => 1
)
)
[accountWide] =>
[factionId] => 2
)
I am attempting to create a function where I can just simply enter the achievement ID, which in this exmple is 7385, and have the parent array which would be [0] => Array (...); returned, so i can then grab the achievement details from that array.
I am not sure if this is really a proper question, as I am not sure as where to start.
So far I have just started breaking the original massive array down into its 10 equally as massive categories, and then searching them each individually, but I would like to just be able to search the main array once instead of searching each category array individually.
ex:
$allAchieves = file_get_contents('http://us.battle.net/api/wow/data/character/achievements');
$allAchieves = json_decode($allAchieves, true);
$generalAchieves = $allAchieves[achievements][0][achievements];
$quests = $allAchieves[achievements][1][categories];
$explorationAchieves = $allAchieves[achievements][2][categories];
$pvp = $allAchieves[achievements][3][categories];
$dungeonAndRaids = $allAchieves[achievements][4][categories];
$professions = $allAchieves[achievements][5][categories];
$reputation = $allAchieves[achievements][6][categories];
$scenarios = $allAchieves[achievements][7][categories];
$worldEvents = $allAchieves[achievements][8][categories];
$petbattle = $allAchieves[achievements][9][categories];
$featsOfStrength = $allAchieves[achievements][10][categories];
Hopefully someone can help, as the other threads I have seen sofar on array searching seem too simple to be of any help as the arrays they are dealing with are nothing to the size of the one I have here.
Thanks for the suggestions, but I solved the issue using a different approach found here:
http://us.battle.net/wow/en/forum/topic/8892160022?page=1#4

Categories