Check for duplicates within multi-di assoc array - php

I have an array like the one below, I need to check for duplicates within the multi-dimensional associative array. I don't think that I really need to say much more, I've already tried array_unique and it happens to think things are duplicates when they clearly aren't.
I'm looking to change this:
array(3) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
[2]=>
array(2) {
["itself"]=>
string(36) "New York"
["status"]=>
string(22) "great"
}
[3]=>
array(2) {
["itself"]=>
string(29) "New York"
["status"]=>
string(18) "great"
}
}
In to this:
array(1) {
[1]=>
array(2) {
["itself"]=>
string(31) "New York"
["status"]=>
string(18) "great"
}
}

Is this an actual output, because the string-lengths don't match... Maybe some hidden data (html-tags, non-printable characters, etc.)?
If not: array_unique wants a string representation:
$result = array_intersect_key(
$input,
array_unique(array_map('serialize',$input)));

$array = array(YOUR ARRAY);
foreach ($array as $key1 => $value1){
foreach ($array as $key2 => $value2){
if($array[$key1] == $array[$key2] && $key1 != $key2){
unset($array[$key1]);
}
}
}

Related

PHP Multudimensional Array foreach

Using PHP and MySQL, I have generated an array called $response.
A var_dump of $response can be seen here.
array(2) {
["OperationRequest"]=>
array(4) {
["HTTPHeaders"]=>
array(1) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "UserAgent"
["Value"]=>
string(14) "ApaiIO [2.1.0]"
}
}
}
["RequestId"]=>
string(36) "f53f381e-efb3-4fef-8e39-4f732b4b463e"
["Arguments"]=>
array(1) {
["Argument"]=>
array(11) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(14) "AWSAccessKeyId"
["Value"]=>
string(20) "KEY"
}
}
[1]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(12) "AssociateTag"
["Value"]=>
string(11) "TAG"
}
}
[2]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "IdType"
["Value"]=>
string(4) "ISBN"
}
}
[3]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "ItemId"
["Value"]=>
string(38) "0751538310,9780141382067,9781305341141"
}
}
[4]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "Operation"
["Value"]=>
string(10) "ItemLookup"
}
}.......so on
A json_encode of the array can be seen here (as requested in a comment).
I'd like to select the Title from these two items. From what I can see this is located at;
Items > Item > ItemAttributes > Author
So, using a foreach loop I have tried the following;
foreach ($response as $item) {
echo $item['Items']['Item']['ItemAttributes']['Title']; // line 2
}
However this returns the following error;
Message: Undefined index: Items. Line Number: 2
Where am I going wrong and what must I change in my code in order to achieve the desired result?
Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Thanks
Try this one, it will help you out. You were are iterating on the wrong key that's why you were not getting desired output.
Try this code snippet herefrom json provide by OP in question
foreach($array["Items"]["Item"] as $key => $value)
{
print_r($value["ItemAttributes"]["Title"]);
echo PHP_EOL;
}
Output:
Panic
Panic
Captain Flinn and the Pirate Dinosaurs: Missing Treasure! (Captain Flinn)
For getting unique titles:
foreach(json_decode($json,true)["Items"]["Item"] as $key => $value)
{
$result[]=$value["ItemAttributes"]["Title"];
echo PHP_EOL;
}
print_r(array_unique($result));
#Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Post your encoded json string to
http://json.parser.online.fr
"+" and "-" button at the right panel should help you read it easily.
//Check Items is not empty
if( !isset($response["Items"]["Item"]) || empty($response["Items"]["Item"]) )
throw New Exception("Empty Item");
foreach($response["Items"]["Item"] as $item){
$title = $item['ItemAttributes']['Title']
}
You should debug as:
foreach ($response as $key => $item) {
if(isset($item['Items'])){ //Check Items index defined
echo $item['Items']['Item']['ItemAttributes']['Title'];
}else{
var_dump($key);
}
}

PHP Multi-Dimensional array search (with array_search)

I am aware of this question, but I have an additional one to search for an array-key. Take a look at this:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Text 1"
["types"]=>
array(3) {
[0]=>
string(7) "Level 1"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor1"
}
}
[1]=>
array(2) {
["name"]=>
string(6) "Text 2"
["types"]=>
array(3) {
[0]=>
string(7) "Level 2"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor2"
}
}
}
This snippet...
echo array_search("Text 2", array_column($response, "name"));
...gives me a 1 for the second array-key, in which the term was found.
But how do I receive the global array-key (0 or 1), if I search for whatisearchfor2, which is stored in the multi-array "types"?
echo array_search("whatisearchfor2", array_column($response, "types"));
...doesn't work.
In your case array_column($response, "types") will return an array of arrays. But to get "global array-key (0 or 1), if you search for whatisearchfor2" use the following approach with array_walk:
$key = null; // will contain the needed 'global array-key' if a search was successful
$needle = "whatisearchfor2"; // searched word
// assuming that $arr is your initial array
array_walk($arr, function ($v,$k) use(&$key, $needle){
if (in_array($needle, $v['types'])){
$key = $k;
}
});
var_dump($key); // outputs: int(1)

Find matching items in array

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.

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;
?>

Categories