Find matching items in array - php

Absolutely doing my head in here over something that I'm sure is very simple...
I have 2 arrays.
$post_cats which are categories that any given post is in.
$ad_cats which is an array of categories in which ads are placed.
Basically, if a post has in its array of selected categories, a category that matches an item in the array of ad categories, then it must return the matching value/item.
$post_cats returns this
array(4) {
[0]=> array(1) { ["slug"]=> string(6) "energy" }
[1]=> array(1) { ["slug"]=> string(6) "global" }
[2]=> array(1) { ["slug"]=> string(8) "identify" }
[3]=> array(1) { ["slug"]=> string(5) "south" }
}
and $ad_cats returns this
array(6) {
[0]=> array(1) { ["slug"]=> string(5) "north" }
[1]=> array(1) { ["slug"]=> string(5) "south" }
[2]=> array(1) { ["slug"]=> string(4) "east" }
[3]=> array(1) { ["slug"]=> string(4) "west" }
[4]=> array(1) { ["slug"]=> string(6) "global" }
[5]=> array(1) { ["slug"]=> string(8) "fallback" }
}
The duplicated item there is "south", so in my mind the value of array_intersect($post_cats, $ad_cats); should be an array with a single item - "south", correct?
But its returning, what seems like, everything in either of the arrays... I can't for the life of me get it to work..
Using the above example, I need to return "south" to a variable.

So you are looking for items that are in both arrays? ...
What about something like this:
function find_duplicate($array1, $array2)
{
$list = array();
foreach($array1 as $value1)
{
foreach($array2 as $value2)
{
if($value1 == $value2) $list[] = $value1;
}
}
return $list;
}

The best way is to convert those arrays in arrays array_intersect can work with.
Considering:
$a; // first array
$b; // second array
then you would go with:
$a1 = array();
foreach ($a as $v) $a1[] = $v['slug'];
$b1 = array();
foreach ($b as $v) $b1[] = $v['slug'];
$c = array_intersect($a1, $b1);
PHP functions usually work with more powerful algorithms than what you may think; therefore it's a good choice to let PHP functions handle this kind of things.

This solution uses array_map to get at the values and takes the intersection of that
function mapper($a)
{
return $a['slug'];
}
$set1 = array_map('mapper', $post_cats);
$set2 = array_map('mapper', $ad_cats);
$result = array_intersect($set1, $set2);
PhpFiddle for testing.

Related

How to group a multidimensional array by multiple subarray values?

I checked this question and answers:
How to group a multidimensional array by a particular subarray value?
He wanted to group results by 'level'. But how would you do it to group it by 'level' first and then by 'type'?
Its pretty straight forward. Loop through $items array. Get each item's level and type and if they are not set yet, initialize them with an empty array. Then just push the "cust" value into the array.
I have given the code below.
I am assuming "$items" is an array which contains the input.
$g = [];
foreach($items as $k => $v) {
$l = $v["level"];
$t = $v["type"];
$c = $v["cust"];
if(!isset($g[$l])) {
$g[$l] = [];
}
if(!isset($g[$l][$t])) {
$g[$l][$t] = [];
}
$g[$l][$t][] = [
"cust" => $c
];
}
var_dump($g);
The output of this code would be like below:
array(3) {
[1]=>
array(1) {
["standard"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8900"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8944"
}
}
}
[3]=>
array(1) {
["premier"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8922"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8816"
}
}
}
[7]=>
array(1) {
["standard"]=>
array(1) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT7434"
}
}
}
}
[P.S.]: You can also use sort to solve this problem easily. That's another way of solving this problem.

Merge a list of single arrays in one array and then sort

I have a variable list of arrays, the list depend of user input. each time the program is called a new set of single arrays is generated.
I been searching for solutions but apparently all solution refer to array of arrays.
Originally the data are from database using:
for ($i = 0; $runrwos= mysql_fetch_assoc($run); $i++) {}
after the loop data are inserted in an array:
$data[$i] = array();
Using a foreach () {} function data are manipulated with mathematical operations to get the desired outcome.
The result will output two string of data,
$A is a numeric data
$B has alphabetic value
$explodA = explode(" ", $A);
$explodB = explode(" ", $B);
Then I combine the result
$new = array_combine($explodA, $explodB);
when I check result I with
var_dump($new);
I get the following result:
array(1) { [1204]=> string(8) "Home2017" }
array(1) { [1183]=> string(8) "Home2018" }
array(1) { [1204]=> string(4) "Stan" }
array(1) { [1204]=> string(7) "Jun2017" }
array(1) { [1173]=> string(9) "APRIL2017" }
.......................................
array(1) { [953]=> string(7) "UNE2018" }
array(1) { [1171]=> string(6) "MAY201" }
I need to sort this data as follow:
array(1) { [953]=> string(7) "UNE2018" }
array(1) { [1171]=> string(6) "MAY201" }
array(1) { [1173]=> string(9) "APRIL2017" }
array(1) { [1183]=> string(8) "Home2018" }
array(1) { [1204]=> string(8) "Home2017" }
array(1) { [1204]=> string(4) "Stan" }
array(1) { [1204]=> string(7) "Jun2017" }
Can someone direct in the right direction?
I guess the solution is simple but I cannot resolve

How to loop through a mulitdimensional array in php?

array(2) {
["names"]=> array(4) {
[0]=> string(4) "Edit"
[1]=> string(6) "Delete"
[2]=> string(8) "Activate"
[3]=> string(10) "Deactivate"
}
["action"]=> array(4) {
[0]=> string(4) "ajax"
[1]=> string(4) "abc"
[2]=> string(4) "def"
[3]=> string(4) "xyz"
}
}
How do i loop through this in a single foreach loop?
Assuming both arrays are of the same size and have the same keys:
foreach($array['names'] as $k => $name) {
$action = $array['actions'][$k];
// do whatever you want to do with $name and $action
}
$newArr = array();
foreach($data['names'] as $i => $val) {
$newArr[$val] = $data['actions'][$i];
}
Or if you want a one liner at that
$newArr = array_combine($data['names'], $data['action']);
I guess the best way is a recursive function which can move through even three dimensions and more
function MoveThroughArray($arr)
{
foreach($arr as $value)
{
if(is_array($value))
MoveThroughArray($value);
else
// Do Something
}
}

How to update a multi-array value?

I have this multidimension array in which I need to update a value. What would be the best way to do so? I tried it with 2 foreach loops but wasn't sure if that was the right approach.
Here is the array in question. I need to update the dollar amount on each sub array (i.e. add 3 to it).
array(6) { ["Ground"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "13.63" }
["3 Day Select"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "25.26" }
["2nd Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "32.43" }
["Next Day Air Saver"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "63.00" }
["Next Day Air"]=> array(2) { [0]=> string(3) "USD" [1]=> string(5) "68.65" }
["Next Day Air Early AM"]=> array(2) { [0]=> string(3) "USD" [1]=> string(6) "103.68" } }
Your foreach loop approach would be correct, unless you expect the data format to change e.g. to have more nested levels. If that were the case, then a recursive function would be best suited.
Also, if the data is expected to remain uniform, you could do this:
foreach( $my_array as $index => $row ){
$my_array[$index][1] += 3;
}
cheers!
foreach ($arr as $k=>$row) {
$arr[$k][1] = floatval($row[1]) + 3;
}
foreach ($array as &$subarray) {
foreach ($subarray as $key=>&$value) {
// do whatever you want with $value
// ...
$value = 'something else'; // example
}
}
Try this:
<?php
foreach($first_array as $first_dem_key)
$first_array[$first_dem_key][1] = $first_array[$first_dem_key][1] + 3;
?>

php global trim $_post

Could you trim all $_POST vars? because i have a very long list right now for trim each var. looks very unprofessional. i thought trim($_POST); would maybe work but it didnt :]
you can do this with array_map:
$_POST = array_map('trim', $_POST);
Works with multi-dimensional arrays
array_walk_recursive($_POST, function (&$val)
{
$val = trim($val);
});
foreach($_POST as &$p) $p = trim($p);
Quick and simple:
foreach($_POST as $key => $val)
{
$_POST[$key] = trim($val);
}
The simplest, and cleanest (in my opinion), is to use the built in array_map function:
array_map('trim', $_POST);
You can also apply a method of your own by passing an array as the first callback-parameter like so:
array_map(array('My_Class', 'staticMethod'), $_POST); // Invoke a static method
array_map(array($myObject, 'objectMethod'), $_POST);
// Invoke $myObject->objectMethod for each element of $_POST
Update based on a comment below
Sometimes the $_POST array may contain arrays. If you want to trim contents of those arrays as well, there are many custom implementations of array_map_recursive available in the PHP manual user notes. Go there and choose one for yourself. If you don't like to take a custom implementation, array_walk_recursive is also a good option for you.
You can do this with array_walk().
Using recursive function you can do that.
PHP
// Static $_POST Array.
$_POST['1']='one ';
$_POST['2']=' two';
$_POST['3'][]=' three ';
$_POST['4'][][]=' four';
$_POST['5'][0][1][3]='five ';
// Recursive function for trim data.
function trim_recursive($array){
$return = array();
foreach($array as $key=>$values){
if(is_array($values)===true){
$return[$key] = trim_recursive($values);
}
else{
$return[$key] = trim($values);
}
}
return $return;
}
// Usage.
$_POST = trim_recursive($_POST);
Output
// Output before trim.
array(5) {
[1]=>
string(4) "one "
[2]=>
string(4) " two"
[3]=>
array(1) {
[0]=>
string(9) " three "
}
[4]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(5) " four"
}
}
[5]=>
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[3]=>
string(5) "five "
}
}
}
}
// Output after trim.
array(5) {
[1]=>
string(3) "one"
[2]=>
string(3) "two"
[3]=>
array(1) {
[0]=>
string(5) "three"
}
[4]=>
array(1) {
[0]=>
array(1) {
[0]=>
string(4) "four"
}
}
[5]=>
array(1) {
[0]=>
array(1) {
[1]=>
array(1) {
[3]=>
string(4) "five"
}
}
}
}

Categories