Removing duplicates from multidimensional array based on the first elements only PHP - php

This is the array
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => John Keys
[postID] => 216
)
[3] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
and I want to remove all duplicates from the artist elements only. Notice that 0 and 2 have the same artist but a different postID. I just want to keep the first occurence of the artist and remove all others. So the result I want to have is
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
I've tried array_unique and also serializing and doing an array_map, nothing seems to work right.

<?php
$array = Array
(
'0' => Array
(
'artist' => 'John Keys',
'postID' => 254
),
'1' => Array
(
'artist' => 'Jay Bloom',
'postID' => 249
),
'2' => Array
(
'artist' => 'John Keys',
'postID' => 216
),
'3' => Array
(
'artist' => 'Angie Belle',
'postID' => 225
)
);
$newarray = array();
foreach($array as $key => $val){
if(!array_key_exists('artist', $newarray)){
$newarray[$val['artist']] = $val;
}
}
echo '<pre>';
print_r($newarray);
Edit: using numeric keys:
$newarray = array();
$temp = array();
foreach($array as $key => $val){
if(!in_array($val['artist'], $temp)){
$temp[] = $val['artist'];
}
if( !array_key_exists(array_search($val['artist'], $temp), $newarray) ){
$newarray[array_search($val['artist'], $temp)] = $val;
}
}

Simple approach:
$result = array();
foreach ($input as $item) {
if (!array_key_exists($item['artist'], $result)) {
$result[$item['artist']] = $item;
}
}

<?php
$a=array(
"0" => array
(
"artist" => "John Keys",
"postID" => "254"
),
"1" => array
(
"artist" => "Jay Bloom",
"postID" => "249"
),
"2" => array
(
"artist" => "John Keys",
"postID" => "216"
),
"3" => array
(
"artist" => "Angie Belle",
"postID" => "225"
)
);
var_dump($a);
for($i=0;$i<count($a);$i++)
{
for($j=$i+1;$j<count($a); $j++)
{
$tmp1=$a[$i]["artist"];
$tmp2=$a[$j]["artist"];
if($tmp1==$tmp2)
{
unset($a[$j]);
}
$tmp3=array_values($a);
$a=$tmp3;
}
}
var_dump($a);
?>

Related

Make associative array of unique values from column containing arrays

Array
(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
)
I have with the above array and I want to convert that array to an unique array as mentioned below, and there should be any duplicate values.
Array(
[History] => "History"
[ACTION] => "ACTION"
[ROMANTIC] => "ROMANTIC"
[Drama] => "Drama"
[Thriller]=>"Thriller"
)
I don't really get how the resulting array makes any sense, but here you are:
Loop through the array, loop through the genres and push items to a new array.
<?
$a = Array
(
[
"id" => 21153,
"genre" => ["History","Drama", "Thriller"]
],
[
"id" => 21152,
"genre" => ["ACTION"]
]
);
$result = [];
foreach($a as $b) {
foreach($b['genre'] as $genre) {
$result[$genre] = $genre; // don't need to check if it exists already, because we'll overwrite it anyway.
}
}
echo "<pre>";
print_r($result);
echo "</pre>";
// output:
Array
(
[History] => History
[Drama] => Drama
[Thriller] => Thriller
[ACTION] => ACTION
)
It can be done by using foreach() loop and in_array() function like below
$myArray=array();
$array = array(
array("id"=>21153,"genre"=>array("History","Drama", "Thriller")),
array("id"=>21152,"genre"=>array("ACTION")),
array("id"=>21151,"genre"=>array("ROMANTIC")),
array("id"=>21150,"genre"=>array("Drama"))
);
foreach($array as $arr){
foreach($arr as $genres){
if(is_array($genres)){
foreach($genres as $elem){
if (!in_array($elem, $myArray))
{
$myArray[$elem]=$elem;
}
}
}
}
}
print_r($myArray);
This is a function that resolves what you ask, though I'm not sure it is quite useful to have value and key being identical. I'm just looping over all genders and add only the ones I don't already have store in returning array. probably a bit dangerous with your code because it is case sensitive
function getGenders(array $rawValues) :array {
$distinctGenders = [];
foreach ($rawValues as $row) {
foreach ($row["genre"] as $gender) {
if (!in_array($gender, $distinctGenders)) {
$distinctGenders[$gender] = $gender;
}
}
}
return $distinctGenders;
}
By doing the changes, I have fixed this,
$responseData = Array(
[0] => Array
(
[id] => 21153
[genre] => ["History","Drama", "Thriller"]
)
[1] => Array
(
[id] => 21152
[genre] => ["ACTION"]
)
[2] => Array
(
[id] => 21151
[genre] => ["ROMANTIC"]
)
[3] => Array
(
[id] => 21150
[genre] => ["Drama"]
)
foreach ($responseData as $data){
$strReplace = str_replace(array('[',']') , '' , $data['genre']);
$explodeData[] = explode(',', $strReplace);
}
And the output after exploding is :
$explodeData = Array
(
[0] => Array
(
[0] => "History"
[1] => "Drama"
[2] => "Thriller"
)
[1] => Array
(
[0] => "ACTION"
)
[2] => Array
(
[0] => "ROMANTIC"
)
[3] => Array
(
[0] => "Drama"
)
)
And finally by the foreach loop :
foreach ($explodeData as $arr) {
foreach ($arr as $genres) {
if (!in_array($genres, $myArray)) {
$myArray[$genres] = $genres;
}
}
}
And finally the required output comes as below :
Array(
["History"] => "History"
["Drama"] => "Drama"
["Thriller"] => "Thriller"
["ACTION"] => "ACTION"
["ROMANTIC"] => "ROMANTIC"
)
Flatten the column of data.
Assign keys from the values (this ensures uniqueness).
Code: (Demo)
$array = [
["id" => 21153, "genre" => ["History", "Drama", "Thriller"]],
["id" => 21152, "genre" => ["ACTION"]],
["id" => 21151, "genre" => ["ROMANTIC"]],
["id" => 21150, "genre" => ["Drama"]]
];
$flat = array_merge(...array_column($array, 'genre'));
var_export(
array_combine($flat, $flat)
);
Output:
array (
'History' => 'History',
'Drama' => 'Drama',
'Thriller' => 'Thriller',
'ACTION' => 'ACTION',
'ROMANTIC' => 'ROMANTIC',
)

Grouping arrays in php and count data

Recently I am working on a project that categorises 'Superheros' and 'Supervillains' based on their 'Franchaise' and origin of 'Superpower'. I want to fetch data from database as as Array #1 and displays them as Array #2 in php.
Array #1
Array
(
[0] => Array
(
[id] => 101
[Name] => Superman
[Franchise] => DC Comics
[Superpower] => Inherent
)
[1] => Array
(
[id] => 908
[Name] => Batman
[Franchise] => DC Comics
[Superpower] => Acquired
)
[2] => Array
(
[id] => 228
[Name] => Wolverine
[Franchise] => Marvel
[Superpower] => Acquired
)
[3] => Array
(
[id] => 158
[Name] => Iron Man
[Franchise] => Marvel
[Superpower] => Acquired
)
[4] => Array
(
[id] => 978
[Name] => Thor
[Franchise] => Marvel
[Superpower] => Inherent
)
)
Array #1 elements have to be grouped based on their 'Franchise' and count how many of them are 'Inherent' or 'Acquired' in terms of 'Superpower'.
Array #2
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Inherent] => 1
[Acquired] => 2
)
)
Here is your code without much logic,
foreach ($array1 as $val) {
if(!isset($array2[$val['Franchise']])) {
$array2[$val['Franchise']] = array('Inherent' => 0, 'Acquired' => 0);
}
$array2[$val['Franchise']][$val['Superpower']]++;
}
print_r($array2);
array_column() function to aggregate an inner key from a 2D array.
array_count_values() function counts all the values of an array.
Use this code snippet for count values:
$a = array ( array ("id" => "101", "Name" => "Superman", "Franchise" => "DC Comics", "Superpower" => "Inherent" ),
array ( "id" => "908", "Name" => "Batman", "Franchise" => "DC Comics", "Superpower" => "Acquired" ),
array ( "id" => "228", "Name" => "Wolverine", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "158", "Name" => "Iron Man", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "978", "Name" => "Thor", "Franchise" => "Marvel", "Superpower" => "Inherent" ));
echo "<pre>";
$return = array();
// first group array values by franchise
foreach($a as $val) {
if (!isset($return[$val['Franchise']])) {
$return[$val['Franchise']] = array();
}
$return[$val['Franchise']][] = $val;
}
$arr = array();
// count elements by key value pair in particular franchise
foreach ($return as $key => $value) {
$tmp = array_count_values(array_column($value, 'Superpower'));
$arr[$key] = $tmp;
}
print_r($arr);
Demo is here
With single and short array_reduce:
// $arr is your initial array
$result = array_reduce($arr, function($r, $v){
if (isset($r[$v["Franchise"]][$v["Superpower"]])) {
$r[$v["Franchise"]][$v["Superpower"]] += $r[$v["Franchise"]][$v["Superpower"]];
} else {
$r[$v["Franchise"]][$v["Superpower"]] = 1;
}
return $r;
}, []);
print_r($result);
The output:
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Acquired] => 2
[Inherent] => 1
)
)

Find Duplicate Multidimensional Array and remove from array php

How to remove multi dimensional array if duplicate.
In this example Barcode is duplicate value of 111 i want to remove this if found duplicate. PLease help Im new to php. Thanks
Output:
Array
(
[0] => Array
(
[Barcode] => 111
[Transaction_No] => 256
)
[1] => Array
(
[Barcode] => 111
[Transaction_No] => 0
)
[2] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
Expected Output:
Array
(
[0] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
This keeps track of the keys of each barcode array item to find duplicates, then uses array_values at the end to fix the array indexing.
<?php
$myArray = array(
array
(
"Barcode" => 111,
"Transaction_No" => 256
),
array
(
"Barcode" => 111,
"Transaction_No" => 0
),
array
(
"Barcode" => 222,
"Transaction_No" => 0
)
);
$barcodeKeys = array();
foreach ($myArray as $key => $arr) {
$code = $arr["Barcode"];
if (!isset($barcodeKeys[$code])) {
$barcodeKeys[$code] = array();
}
$barcodeKeys[$code][] = $key;
if (count($barcodeKeys[$code]) > 1) {
foreach ($barcodeKeys[$code] as $dupKey) {
if (isset($myArray[$dupKey])) {
unset($myArray[$dupKey]);
}
}
}
}
$myArray = array_values($myArray);
print_r($myArray);
Output
Array
(
[0] => Array
(
[Barcode] => 222
[Transaction_No] => 0
)
)
Fast approach to your question:
<?php
$barcodes = array(array( 'Barcode' => 111,'Transaction_No' => 256),array('Barcode' => 111,'Transaction_No' => 0),array('Barcode' => 222,'Transaction_No' => 0),array('Barcode' => 333,'Transaction_No' => 0));
$result = array();
$exist = array();
foreach($barcodes as $key => $item){
if( in_array( $item['Barcode'], array_values( $exixt ) ){
unset( $result[ array_search ( $item['Barcode'], $exist ) ] );
} else {
$result[ $key ] = array('Barcode' => $item['Barcode'],'Transaction_No' => $item['Transaction_No'] );
$exist[ $item['Barcode'] ] = $key;
}
}
var_dump($result);

merging mutidimensional arrays

I have an array that looks like this:
getting array need to convert array as same key value as 0
foreach($array as $key=>$id){
$consumer_data[]=$this->App_model->get_session($id);
}
print_r($consumer_data);
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
)
[1] => Array
(
[0] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
i want to implement array like this in same key value as 0
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
[3] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?
You can use array_merge():
$new_array[0] = array_merge($array[0], $array[1]);
Where $array is the first array.
SEE DEMO
OR for a more dynamic approach:
$new_array = array(0 => array());
foreach($array as $a) {
$new_array[0] = array_merge($new_array[0], $a);
}
SEE DEMO 2
The simpliest solution is to do it with:
$input = array(
array(
array('ConsumerID' => 1, 'name' => 'asdfd'),
array('ConsumerID' => 5, 'name' => 'test'),
array('ConsumerID' => 4, 'name' => 'test1'),
),
array(
array('ConsumerID' => 4, 'name' => 'test4'),
),
);
$output = array(
array()
);
foreach ($input as $data) {
$output[0] = array_merge($output[0], $data);
}
Try this->
$newArray = array();
foreach($values as $key=>$val){
$newArray [0][$key]=$val;
}
print_r($newArray);
Check this:
<?php
$arr[0] = array(0 => array("ConsumerID" => 1, "name" => "Ni"), 1 => array("ConsumerID" => 2, "name" => "Ab"));
$arr[1] = array(1 => array("ConsumerID" =>5, "name" => "GE"), 1 => array("ConsumerID" => 6, "name" => "DB"));
$new = array();
foreach($arr as $key => $value) {
foreach($value as $innerkey => $innervalue) {
$new[0][] = $innervalue;
}
}
print_r($new);
?>

Count occurrences of a value inside a multidimensional array

so i retrieve a json, convert it into an array and i got this output:
Array
(
[Sid] => 23888555
[pages] => Array
(
[0] => Array
(
[id] => 13111071
[name] => Page 1
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
[2] => Array
(
[SlotId] => 7
[info] => Array
(
[id] => 5267
[color] => green
)
)
)
)
[1] => Array
(
[id] => 13111072
[name] => Page 2
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
)
)
)
)
I have no problem reading it whatsoever, what i wanna do is count for every page how many similar "last" id i got.
Exemple :
[pages][0][slots][0][info][id]
[pages][0][slots][1][info][id]
[pages][0][slots][3][info][id]
For the page 1, I wanna compare these 3 ids between them and count the occurrences.
[pages][1][slots][0][info][id]
[pages][1][slots][1][info][id]
For the page 2, I wanna compare these 2 ids between them and count the occurrences.
The output i want looks like this :
page 1 -> 1x5247
-> 2x5267
page 2 -> 1x5247
-> 1x5267
EDIT :
I tried using
foreach ($data['pages'] as $item) {
foreach ($item['slots'] as $slotnumber => $value) {
print_r(array_count_values($item['slots'][$slotnumber]['info']));
}
}
which returns me this :
Array ( [5247] => 1 [red] => 1 )
Array ( [5267] => 1 [blue] => 1 )
Array ( [5267] => 1 [green] => 1 )
So i think i might be able to use this but i don't know how.
I manually declared the array and then created the countstuff() function. This should work for you. I tested it and it work on my end. After going through all this trouble, I really do appreciated it if you choose my answer and up vote it.
<?php
$data = Array("Sid" => "23888555", "pages" => Array("0" => Array("id" => "13111071", "name" => "Page 1", "slots" => Array("0" => Array("SlotId" => "6", "info" => Array("id" => "5247", "color" => "red")), "1" => Array("SlotId" => "4", "info" => Array("id" => "5267", "color" => "blue")), "2" => Array("SlotId" => "7","info" => Array("id" => "5267", "color" => "green")))),
"1" => Array
(
"id" => "13111072",
"name" => "Page 2",
"slots" => Array
(
"0" => Array
(
"SlotId" => "6",
"info" => Array
(
"id" => "5247",
"color" => "red"
)
),
"1" => Array
(
"SlotId" => "4",
"info" => Array
(
"id" => "5267",
"color" => "blue"
)
)
)
)
)
);
//End of array declaration
//Now the really convoluted coding starts
//Create a function
function countstuff($yourarray){
foreach($yourarray as $mainarraykey => $mainarray){
if($mainarraykey == "pages"){
foreach($mainarray as $pageskey => $pagesarray){
//echo "Page \"$pageskey\"<br/>";
foreach($pagesarray as $pagessubarraykey => $pagessubarray_array){
if($pagessubarraykey == "slots"){
foreach($pagessubarray_array as $slotskey => $slots){
foreach($slots as $slotssubkey => $slotssub){
if($slotssubkey == "info"){
foreach($slotssub as $key => $value){
if($key == "id"){
//echo $value."<br/>";
$pages[$pageskey][] = $value;
}
}
}
}
}
}
}
}
}
}
return $pages;
}
//Execute the countstuff() function
$output = countstuff($data);
function showresults($input){
foreach($input as $pagekey => $page){
echo "Page $pagekey:<br/>";
$results = array_count_values($page);
foreach($results as $resultkey => $result){
echo $result."x".$resultkey."<br/>";
}
echo "<br/>";
}
}
showresults($output);
?>
I tried some things let me know what you guys think of this.
I get every id then enter them into an array then use array_count_values
$array_ids = array();
foreach ($data['pages'] as $item) {
$numberOfElements = count($item['slots']);
$z= 0;
foreach ($item['slots'] as $slotnumber => $value) {
$array_ids[$z] = $item['slots'][$slotnumber]['info']['id'];
// search for occurrences when the array is full
if (count($array_ids) == $numberOfElements) {
var_dump(array_count_values($array_ids));
// reset the array to 0 every time we loop through the whole infos
$array_ids = array();
}
$z++;
}
}
This seems to work for every page.
array (size=2)
5267 => int 2
5247 => int 1
array (size=2)
5267 => int 1
5247 => int 1

Categories