PHP Unique Values from Column in Array - php

I have an array that is generated from a SQL query that I run. It looks like the following:
$arr[$i]['id'] = $id;
$arr[$i]['name'] = $name;
$arr[$i]['email'] = $email;
How can I get the unique values from the email column? I appreciate the help.

The best answer is :
array_unique(array_column($arr, 'email'))

Either filter it in your column using the DISTINCT method in MySQL, or use something like
$uniqueEmails = array();
foreach($arr as $array)
{
if(!in_array($array['email'], $uniqueEmails)
$uniqueEmails[] = $array['email'];
}

Since PHP 5.5, a new function called array_column() is also available.
You can use it following way:
$allEmails = array_column($arr, 'email');
$uniqueEmails = array_unique($allEmails);

Remove duplicates from array comparing a specific key
Consider the same array but id of 3rd index is different:
$all_array = Array
(
[0] => Array
(
[id] => 1
[value] => 111
)
[1] => Array
(
[id] => 2
[value] => 222
)
[2] => Array
(
[id] => 3
[value] => 333
)
[3] => Array
(
[id] => 4
[value] => 111
)
)
Now, both 1 & 4 have same values. So we want to remove any of them:
$unique_arr = array_unique( array_column( $all_array , 'value' ) );
print_r( array_intersect_key( $all_array, $unique_arr ) );

If you get the list sorted by email from SQL you can improve performance by looping through the array like Gareth does, but instead only compare current email address with the last inserted email address. Below is a code example for this:
$uniqueEmails = array();
$lastemail = '';
foreach($arr as $array)
{
if($array['email'] != $lastemail)
{
$uniqueEmails[] = $array['email'];
$lastemail = $array['email'];
}
}

Related

select query to make one column as key in mysql

I need the array as (2) from a single query
can anyone help ?
1. Array
(
[0] => Array
(
[crop_id] => 3
[crop_name] => Barley
)
2. Array
(
[0] => Array
(
[Barley] => 3
)
)
Don't know about query but you can do that simply using array_map()
$array[] = array('crop_id' => 3, 'crop_name' => "Barley");
$result = array_map("myfunction",$array);
print_r($result);
function myfunction($v)
{
$data = [];
$data[$v['crop_name']] = $v['crop_id'];
return $data;
}
Let's suppose you have stored your data in array named as crop_data like
$crop_data[0][crop_id]=3;
$crop_data[0][crop_name]='Barley';
....
$crop_data[n][crop_id]=187;
$crop_data[n][crop_name]='Wheat'
Try this code:
$new_crop_result=array()
foreach($crop_data as $key=>$record)
{
$new_crop_result[$key][$record[crop_name]]=$record[crop_id];
}

How to compare different arrays?

I need to show the email address, first and last names of users who are not registered in my new database.
I selected three columns of my old database and three columns of my new database. I created two arrays and each receives the result of the query.
But when the comparing is displaying all users, the comparison is not made.
Check my code:
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[] = $array2;
}
foreach ($portal_old as $portal) {
if(!in_array($portal, $portal_new)){
$result[] = $portal;
}
}
Assuming email address should be able to uniquely identify a registered user, you can use email address as a key as you build your array of results from each database.
while($array = $resultado->fetch_array(MYSQLI_ASSOC)){
$portal_old[$array['email']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_ASSOC)){
$portal_new[$array2['email']] = $array2;
}
In order for this to work, you will need to either use MYSQLI_ASSOC instead of MYSQLI_NUM when fetching, and specify the name of the email column when building your array, or if you are using MYSQLI_NUM, specify the numeric index of the email column.
Then you can use array_diff_key to easily find the result you are looking for.
$result = array_diff_key($portal_old, $portal_new);
This works, John Smith here gets in $result while Joe Black doesn't:
<?php
$name = array(0 => 'john', 1 => 'smith');
$portal_old[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_old[] = $name;
//print_r($portal_old);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) [1] => Array ( [0] => joe [1] => black ) )
$name = array(0 => 'jason', 1 => 'mill');
$portal_new[] = $name;
$name = array(0 => 'joe', 1 => 'black');
$portal_new[] = $name;
//print_r($portal_new);
//shows: Array ( [0] => Array ( [0] => jason [1] => mill ) [1] => Array ( [0] => joe [1] => black ) )
foreach($portal_old as $key=>$value) {
if(!in_array($value[0], $portal_new[0]) && !in_array($value[1], $portal_new[1])) {
$result[] = $value;
}
}
print_r($result);
//shows: Array ( [0] => Array ( [0] => john [1] => smith ) )
?>
It's because the results of $portal_old and $portal_new are multidimensional arrays, you need to compare by looking inside the arrays of the arrays.
This will work for you :
$i = $j = 0;
while($array = $resultado->fetch_array(MYSQLI_NUM)){
$portal_old[$i][$array['0'].' | '.$array['1'].' | '.$array['2']] = $array;
}
while($array2 = $resultado2->fetch_array(MYSQLI_NUM)){
$portal_new[$j][$array2['0'].' | '.$array2['1'].' | '.$array2['2']] = $array2;
}
// Get only array keys
$old_arr_key = array_keys($portal_old[0]);
$new_arr_key = array_keys($portal_new[0]);
// Result
$result = array_diff($new_arr_key,$old_arr_key);
print_r($result);

How get a object by id from arrays of object?

Assuming that I have an array of objects like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 26-295-1006
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 12-330-1000
[qty] => 2
[price] => 230.35
)
And I have another array of object hat looks like this:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I want to loop through the 2nd array of objects and get the 'itemVendorCode' and then use it as the 'id' to get the object from the first array of objects. Is there a way to obtain what I want without looping the first array? Looping is very costly in my use-case.
You will have to use loops in any case, even if those loops are hidden within PHP built-in functions.
For instance:
$codes = array_map(function ($item) { return $item->itemVendorCode; }, $array2);
$items = array_filter($array1, function ($item) use ($codes) { return in_array($item->id, $codes); });
// $items contains only elements from $array1 that match on $array2
If this will be more efficient than using regular loops is hard to tell.
Since you are aparently trying to code what is supposed to be a DBMS's job, I recommend you export those tables to a database server such as MySQL instead and let it work its magic on those "JOINs".
Answering your comment, you could merge with something like this:
$result = array();
foreach ($array1 as $item1)
foreach ($array2 as $item2)
if ($item1->id == $item2->itemVendorCode)
$result[] = (object)array_merge((array)$item1, (array)$item2));
$result will contain a new set of objects that merge properties from both $array1 and $array2 where they intersect in id == itemVendorCode.
Do you need first arrays index keys? if not you could iterate throuh first array once and set key to id. Something like:
foreach ($items as $key => $item) {
$items[$item->id] = $item;
unset($items[$key]);
}
Here is another direct approach to solve this problem, even better than the one I proposed earlier:
// you got the $itemVendorCode from looping through the second array, let say :
$itemVendorCode = "89-605-1250";
// I'm assuming that you converted the array of objects in into accessible multidimensional array
// so the $first_array would look like :
$first_array= array (
array (
"id" => "10-423-1176",
"qty" => 2,
"price" => 12.6
),
array (
"id" => "10-423-1176",
"qty" => 5,
"price" => 25
),
array (
"id" => "89-605-1250",
"qty" => 12,
"price" => 30
)
);
// Now you can filter the first array using
$filter = function ($player) use($itemVendorCode) {
return $player ['id'] == $itemVendorCode;
};
$filtered = array_filter ( $first_array, $filter );
// print the price of the matching filtered item
print $filtered[key($filtered)]['price'] ;
You can use the array_map and array_filter() function to achieve that.
Try with this code:
<?php
$first = array();
$first[0] = new stdClass;
$first[0]->id = '89-605-1250';
$first[0]->qty = 2;
$first[0]->price = 12.6;
$first[1] = new stdClass;
$first[1]->id = '89-575-2354';
$first[1]->qty = 24;
$first[1]->price = 230.35;
$last = array();
$last[0] = new stdClass;
$last[0]->internalId = 14062;
$last[0]->itemVendorCode = '89-605-1250';
$last[1] = new stdClass;
$last[1]->internalId = 33806;
$last[1]->itemVendorCode = '89-575-2354';
$ids = array_map(function($element){return $element->itemVendorCode;}, $last);
$to_find = $ids[0];
$object = array_filter($first, function($element){global $to_find; return $element->id == $to_find ? true: false;})[0];
print_r($object);
?>
Output:
stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 12.6
)
try using array_search:
http://php.net/manual/en/function.array-search.php
foreach($array2 as $key=>$item) {
$firstArrayObjectKey = array_search($item['itemVendorCode'], $array1);
//... do something with the key $firstArrayObjectKey
}
In this case you'll need to loop through the first array to get the itemVendorCode.
Right after that you can use the itemValue you got from the previous process to search in a reduced array of the first object using array_reduce function:
http://php.net/manual/en/function.array-reduce.php

Array unique values PHP

I want to find the Unique values by username:
so the resulting array would be [0] =>JakeP, [1]=>TomC
My code currently works, but I was wondering is there a better way to accomplish this task with less loops, or using array_unique function?
Array
(
[0] => Array
(
[ID] => 3
[Username] => TomC
[Project_Name] => Inventory
)
[1] => Array
(
[ID] => 4
[Username] => JakeP
[Project_Name] => Inventory
)
[2] => Array
(
[ID] => 2
[Username] => TomC
[Project_Name] => Stocks
)
[3] => Array
(
[ID] => 1
[Username] => Tomc
[Project_Name] => Stocks
)
)
My code which works is :
$names_filter = array();
foreach($latest_projects as $project)
{
if(empty($names_filter))
{
$names_filter[] = $project['Username'];
}
else {
foreach($names_filter as $key=>$value)
{
if($value == $project['Username'])
{ break; }
else
{
$names_filter[] = $project['Username'];
}
}
}
}
If you're using PHP >= 5.5 you can take advantage of the array_column() function:
$uniqueNames = array_unique(
array_column($myArray, 'Username')
);
Prior to PHP 5.5, you can use:
$uniqueNames = array_unique(
array_map(
function($value) {
return $value['Username'];
},
$myArray
)
);
You can use the in_array function to simplify your code. Example:
$names_filter = array();
foreach($latest_projects as $project)
{
if(!in_array($project['Username'], $names_filter))
{
$names_filter[] = $project['Username'];
}
}
The in_array() function checks for the existence of a value in an array. So the foreach loop will only add a project username to the $names_filter array if it's not in the array. The output should be a list of unique usernames in the $names_filter array.
We can loop through $latest_projects and store each user name to new array ($filter). Since array can't have two elements with same keys, if the key exists it will be overwritten.
$filter = array();
foreach ($latest_projects as $project)
{
$filter[$project['Username']] = 1;
}
$filter = array_keys($filter);
I can't speak to the performance of this over other solutions, but a similar effect can be achieved with the use of array_map and array_unique. It's not as readable either though, which is just as important.
$uniqueUsers = array_unique(array_map(function ($p) { return $p['Username']; }, $latest_projects));

PHP switch array values

I have a very simple array like this:
Array ( [friend_id] => 180 [user_id] => 175 )
What I want to do is just to switch the values, in order to be come this:
Array ( [friend_id] => 175 [user_id] => 180 )
Is there any elegant NON STATIC way in PHP to do it?
you can use array_combine and array_reverse
$swapped = array_combine(array_keys($arr), array_reverse(array_values($arr)));
No. Use a temporary value:
$temp = $array['friend_id'];
$array['friend_id'] = $array['user_id'];
$array['user_id'] = $temp;
A bit longish, but I think it satisfies you requirements for 2 element arrays, just as you used in your example:
// your input array = $yourarray;
$keyarray = array_keys($yourarray);
$valuearray = array_values($yourarray);
/// empty input array just to make sure
$yourarray = array();
$yourarray[$keyarray[0]] = $valuearray[1];
$yourarray[$keyarray[1]] = $valuearray[0];
Basically Orangepill's answer done manually...
How about using array_flip?
array array_flip ( array $trans )
$myar = array('apples', 'oranges', 'pineaples'); print_r($myar);
print_r(array_flip($myar));
Array
(
[0] => apples
[1] => oranges
[2] => pineaples
)
Array
(
[apples] => 0
[oranges] => 1
[pineaples] => 2
)
$tmp = $array['user_id'];
$array['user_id'] = $array['friend_id'];
$array['friend_id'] = $tmp;

Categories