array_diff() removing partial values - php

I am developing a hashtag search system on Instagram. And I get a list of users with their posts in the following form:
username1-idposts123455665435, username2-idposts45634563456, username3-idposts276544234....
I set up an array to be able to work with the display on my page, with the code, where $getRelatorio are the users above.
$base_array_split = preg_split("/,\s/", $getRelatorio);
$base_array_filtro = array_filter($base_array_split);
foreach($base_array_filtro as $explode_usuarios_array)
{
$explode_usuarios = explode("-", $explode_usuarios_array);
$array1[] = array(
$explode_usuarios[0], //get username
$explode_usuarios[1] // ger post id
);
}
Everything works fine. But I want to implement a Black List system, to block the display of users that the customer does not want to see.
I store it in the database in the same way, separated by a comm and to work, I also assemble an array.
$base_array_lista = preg_split("/,\s/", $listanegra);
$base_array_filtro_lista = array_filter($base_array_lista);
foreach($base_array_filtro_lista as $explode_lista_negra)
{
$is_array[] = array(
$explode_lista_negra //get username
);
}
$array2 = isset($is_array) && is_array($is_array) ? $is_array : []; //if empty
Now, I am using the following to exclude the users that the customer has blacklisted:
$arrayfinal = array();
foreach($array1 as $arr)
{
$arrayfinal[] = array_diff($arr, array_column($array2, 0));
}
$array = array_filter($arrayfinal);
The difference between the two arrays is that one has the post id.
The result:
I am able to remove the username, but the post ID is still displayed in the array.
If i remove array_column($array2, 0) it doesn't work.
If i use array_diff_assoc it doesn't work either
var_dump:
[0] => Array
(
[0] => username1
[1] => 2577195852001190087
)
[1] => Array
(
[0] => username2
[1] => 2577195809822230254
)
[2] => Array
(
[0] => 2577195306530472731 //username removed, bud post id is not - need to remove that too
)
var_dump expected:
[0] => Array
(
[0] => username1
[1] => 2577195852001190087
)
[1] => Array
(
[0] => username2
[1] => 2577195809822230254
)

You can index on username or postid and do it like this (indexed on postid):
foreach(explode(', ', $string) as $values) {
$parts = explode('-idposts', $values);
$result[$parts[1]] = $parts[0];
}
$blacklist = ['username3'];
$result = array_diff($result, $blacklist);
Or using the format you have:
foreach(explode(', ', $string) as $values) {
$parts = explode('-idposts', $values);
$result[$parts[0]] = $parts;
}
$blacklist = ['username3'];
$result = array_diff_key($result, array_flip($blacklist));

Here's another way.. flatten the arrays using json_encode, comparing then reinflating.
View a demo here:
https://www.tehplayground.com/IcpKbUyFltbXhNQp
<?php
$array1 = array(
array("username1", "2577195852001190087"),
array("username2", "1577195852001190087"),
array("username3", "3577195852001190087")
);
$array2 = array(
array("username2", "1577195852001190087"),
array("username3", "3577195852001190087")
);
$a=array_map(function($v) { return json_encode($v); }, $array1);
$b=array_map(function($v) { return json_encode($v); }, $array2);
$arrayfinal = array_map(function($v) { return json_decode($v); }, array_diff($a, $b) );
$array = array_filter($arrayfinal);
print_r($array);

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

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',
),
)

unique pairs storing in array in php

I am stuck at a scenerio where i need to save user input like... (in 1 go i get these reuslt)
$string = "'a':'php,'b':'.Net' ...
'c' 'java'
'c' 'php'
'c' 'java'
'a' 'php'
'a' 'java' ";
Now i need to store all these values in a database (only unique pairs).
WHat i tried so far, exploded $string with "," and stored everything in an array like
$array["a"] = "php";...but this will overwrite a = java too... //problem
I don't need to check in database that if they exist already or not..this is handled already (all dumped data in one go get a unique identifier).
All i need to do is to get unique pairs and dump into database...means
a = php, a = java, b = .net, c = java, c=php
Only solution i could see was...after exploding ...check for the pair in db against new unique identified...mysql_num_rows...if does not exist then dump else dont...
Is there any easy way...??
The best way for your purpose is to create the multidimensional array
<?php
$string = "'a':'php','b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$array = array();
$temp_arr = explode(",", $string);
foreach($temp_arr as $key=>$value)
{
list($tempkey,$tempValue) = explode(':', $value);
$tempKey = trim($tempkey,"'");
$tempValue = trim($tempValue,"'");
$array[$tempKey][] = $tempValue;
}
$array = array_map('array_unique',$array);
echo "<pre>";
print_r($array);
?>
output will be
Array
(
[a] => Array
(
[0] => php
[2] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)
$string = "'a':'php,'b':'.Net','c':'java','c':'php','c':'java','a':'php','a':'java'";
$temp = array_map(function($item) {
list($key, $value) = explode(':', $item);
return array(str_replace("'", "", $key) => str_replace("'", "", $value));
}, explode(",", $string));
$results = array();
foreach($temp as $item) {
$key = key($item);
if(!isset($results[$key]) || !in_array($item[$key], $results[$key])) {
$results[$key][] = $item[$key];
}
}
print_r($results);
Output:
Array
(
[a] => Array
(
[0] => php
[1] => java
)
[b] => Array
(
[0] => .Net
)
[c] => Array
(
[0] => java
[1] => php
)
)

remove dashes from each value in an array, then rebuild array

Im having a lot of trouble with this, and I'm now sure why.
I have a dynamic array, that can consist of 1 or more values:
[array] => Array
(
[0] => blurb
[1] => news
[2] => entertainment
[3] => sci
[4] => diablo-3
)
Here is my model
public function create_session_filter($filters)
{
$array = split("\|", $filters);
$filter['filter'] = $array;
$this->session->unset_userdata('filter');
$this->session->set_userdata($filter);
}
When the array $filters is run, i need to remove any dashes from any of the individual array values and replace them with spaces.
This is producing some funky results:
public function create_session_filter($filters)
{
$filterarray = array();
$array = split("\|", $filters);
foreach ($array as $filter)
{
print_r($filter);
$filterspace = implode(' ', explode('-', $filter));
$filterarray = array_push($filterarray, $filterspace);
}
$filter['filter'] = $filterarray;
$this->session->unset_userdata('filter');
$this->session->set_userdata($filter);
}
What is the correct way to do this?
Thanks
All of the exploding and imploding isn't really necessary. Nor would you need to create a new array. You can cycle through your values by reference, and modify them in a one-liner:
$array = array( "blurb", "news", "diblo-3" );
$array = str_replace( "-", " ", $array );
Which outputs:
Array
(
[0] => blurb
[1] => news
[2] => diblo 3
)
Demo: http://codepad.org/up0VoZ21

Categories