PHP - Delete all duplicates in array - php

How can I delete duplicates from multiple arrays?
pinky and cocos are double in my array. All words which are double, must be removed. If those are removed, I will put these words in my select.
I get those words from my database.
The query:
$queryClient = " SELECT DISTINCT `clients` FROM `reps` WHERE `clients` != ''";
This is my code:
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['clients']);
echo '<pre>'; print_r($names); echo '</pre>';
}
Result: (Those food words are just an example)
Array
(
[0] => chocolate
)
Array
(
[0] => vanilla
[0] => cocos
)
Array
(
[0] => strawberry
)
Array
(
[0] => pinky
[1] => watermelon
[2] => melon
[3] => cocos
)
Array
(
[0] => pinky
)
Array
(
[0] => dark-chocolate
)
I tried this in my while loop but it did not work:
$array = array_unique($names, SORT_REGULAR);
How can I remove all duplicates? Can you help me or do you have a solution for my problem? Help.

Here's a one-liner:
print_r(array_unique(call_user_func_array('array_merge', $names)));
First merge all subarrays into one, then get unique values.
Full example:
$names = array();
while($row = mysql_fetch_assoc($resultClient)){
$names[] = explode(",", $row['clients']);
}
print_r(array_unique(call_user_func_array('array_merge', $names)));

You can just do a little trick:
Flatten, count and then remove all except the last.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flatArray = [];
foreach($it as $v) {
$flatArray[] = $v; //Flatten array
}
//Note you can do array_unique on the flat array if you also need to flatten the array
$counts = array_count_values($flatArray); //Count
foreach ($array as &$subarray) {
foreach ($subarray as $index => $element) {
$counts[$element]--;
if ($counts[$element] > 0) { //If there's more than 1 left remove it
unset($subarray[$index]);
}
}
}
This will remove duplicates nested exactly on the 2nd level without flattening the original array.
http://sandbox.onlinephpfunctions.com/code/346fd868bc89f484dac48d12575d678f3cb53626

first you need to join your array before you can filter out the duplicates:
<?php
$allNames = [];
while($row = mysql_fetch_assoc($resultClient)){
$names = explode(",", $row['food']);
$allNames[] = $names;
}
$allNames = array_merge(...$allNames); //Join everything to a one dimensional array
$allNames = array_unique($allNames); // Only keep unique elementes
print_r($allNames);

Related

How to remove data from a single array after comparing it with an array from a database?

So currently, I have a single array ($array1) that I want to compare with an array ($array2) that I created by retrieving data from the database. Technically speaking, $array2 is multidimensional since I used a while loop with mysqli_fetch_assoc. Is there any way to compare these two arrays with each other? My end goal is to compare these two arrays, and to only remove the data from the single array ($array1) when there is a mismatch. By that, I mean only to remove the data that doesn't match with $array2.
For example:
$array1 = Array ( [0] => cookies [1] => chicken [2] => tesla )
$array2 = Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel )
So in this case, $array2 came from the database, and $array1 is given. So how can I compare these two arrays in order to get this array back: $arraynew = Array ( [0] => tesla )?
Note:
So far I have tried this:
$query = "SELECT name FROM tagsbreedables WHERE idTagCategory = 6";
$result10 = mysqli_query($conn, $query);
if (mysqli_num_rows($result10) > 0) {
while ($row = mysqli_fetch_assoc($result10)) {
$bloem = $datas4['name'] = $row;
print_r($row);
$subarray = array_column($bloem,'name');
print_r($array3);
}
}
$aMust = explode(" ", $_GET['q']);
$searchTermBits = array();
foreach ($aMust as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "$term";
}
}
$matches = $searchTermBits;
$test = array($subarray, $matches);
foreach ($test as $key => $subarray) {
foreach ($subarray as $subsubarray) {
foreach ($matches as $match) {
if ($subsubarray == $match) {
$finalarr[$key][] = $subsubarray;
}
}
}
}
print_r($finalarr[0]);
$pindakaas = implode('","',$finalarr[0]);
echo $pindakaas;
The code works great, it's just that I don't know how to get data from the database into $subarray... I just get Array ( ) Array ( ) ...for $array3
if $array2 is an array of arrays like below
array(Array ( [name] => tesla ) Array ( [name] => bmw ) Array ( [name] => opel ))
you can use the function array_column to get the values from a single column, in this case name.
$array3 = array_column($array2,'name')
the above should give you
array(0=>tesla,1=>bmw,2=>opel)
you can then use array_intersect to compare them
$arraynew = array_intersect($array1,$array3);

displaying items in array ordered by id inside string

I want to display items in an array separately, ordered by groups.
The items are stored in a string like this:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
Then I display them like this:
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
echo substr($item,2); //substr to get rid of the group id
}
EDIT: solution
if(strpos($item, "1:")!==false){
echo substr($item,2);
}
You could perform another explode on your initial array on the colon, seperate the number and the value, then feed them into a array using the number as the key, eg:
$itemsString = "1:asd, 1:wer, 2:dfg, 3:gfg, 3:sdfss"; //and so forth
$sorted_array = [];
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item) {
$subItemsArray = explode(":", $item);
$sorted_array[$subItemsArray[0]][] = $subItemsArray[1];
}
print_r($sorted_array);
Which would mean $sorted_array would be pre-sorted for you (or easily sortable with ksort()):
Array
(
[1] => Array
(
[0] => asd
[1] => wer
)
[2] => Array
(
[0] => dfg
)
[3] => Array
(
[0] => gfg
[1] => sdfss
)
)
you can display them like this
$itemsArray = explode(", ", $itemsString);
foreach($itemsArray as $item){
if(strpos($item, "1:") || strpos($item, "1:") ===0 ){
echo substr($item,2)
;}
}

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

Unique values of a multidimensional array while inside a foreach loop

I am working within a foreach loop and PARTS my code looks like this:
foreach ($query->rows as $row) {
$myarray = explode(",",$row['text']);
print_r($myarray);
}
The Output result of the above is this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Combo
)
Array
(
[0] = Charcoal
[1] = Propane
[2] = Natural Gas
[3] = Combo
)
Array
(
[0] = coal
)
Array
(
[0] = Natural Gas
[1] = Wood
)
Yes I see there are similar questions to this. But none of their answers seem to work for me. I'm thinking it might be because I am working inside an foreach loop. Either way, I was wondering if there was a way to get my output above to look like this:
Array
(
[0] = Charcoal
[1] = Natural Gas
[2] = Combo
)
Array
(
[0] = Propane
)
Array
(
[0] = Coal
)
Array
(
[0] = wood
)
All the duplicates gone, without loosing the formatting of this array. Code I have tried.. but "maybe" wrong was:
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
EDIT for Sharanya Dutta:
I have alot of other code, but basically this is where Im trying to use it.
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
$output[$row['attribute_id']]['values'][] = $diff; // <--- USE IT HERE
}
Use an array ($arr in the following code) to store the values and print_r only those values which are different from the already stored values:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
if($diff !== array()) print_r($diff);
$arr = array_merge($arr, $_arr);
}
DEMO
You may even use $diff after the last line in the foreach loop:
$arr = array();
foreach($query->rows as $row){
$_arr = explode(",", $row["text"]);
$diff = array_values(array_diff($_arr, $arr));
$arr = array_merge($arr, $_arr);
if($diff !== array()) print_r($diff);
}
DEMO
As you iterate the result set rows and explode the text string, filter the individual values in the current row against all values in all previously encountered rows.
If there are any individual values encountered for the first time, then save the unique values of that row as a new row in the result array.
Code: (Demo)
$resultSet = [
['text' => 'Charcoal,Natural Gas,Combo'],
['text' => 'Charcoal,Propane,Combo'],
['text' => 'Charcoal,Propane,Natural Gas,Combo'],
['text' => 'coal'],
['text' => 'Natural Gas,wood'],
];
$result = [];
foreach ($resultSet as $row) {
$clean = array_diff(
explode(',', $row['text']),
...$result
);
if ($clean) {
$result[] = array_values($clean);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 'Charcoal',
1 => 'Natural Gas',
2 => 'Combo',
),
1 =>
array (
0 => 'Propane',
),
2 =>
array (
0 => 'coal',
),
3 =>
array (
0 => 'wood',
),
)

Searching through a list of numbers which came from mysql query result

$save_planet3 = "SELECT saver_id FROM save_planet
WHERE saver_id = '".($_SESSION['user_id'])."'
AND map = 1 ORDER BY time_saved DESC";
$save_planet2 = mysql_query($save_planet3) or trigger_error("SQL", E_USER_ERROR);
while ($list = mysql_fetch_array($save_planet2)) {
$saver_id = $list['saver_id'];
When I echo $saver_id I'm getting a list of numbers
3112 3112 3112 3112
I'm trying to do a check if $planet_id is equal to any of these numbers
So I figure the only way to do this is to put these numbers in an array with keys first. So I tried to explode it but it doesn't give each one a different key I noticed.
$check = explode(",", $saver_id);
print_r($check);
Array ( [0] => 3112 )
Array ( [0] => 3112 )
Array ( [0] => 3112 )
Array ( [0] => 3112 )
Once I get this in a workable array I should be able to do this right
foreach($array as $key => $value) {
if ($planet_id == $value) {
//something happends
why not store the result set values into an array inside of the while loop?
$arr = array();
while ($list = mysql_fetch_array($save_planet2)) {
$saver_id = $list['saver_id'];
$arr[] = $saver_id;
}
print_r($arr);
You can also use in_array() to check for the value existence.

Categories