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);
Related
I have 3 explode statements:
$emails = explode(',', $row['email']);
$firstnames = explode(',', $row['first_name']);
$lastnames = explode(',', $row['last_name']);
each explode produces three (3) arrays:
//emails
Array
(
[0] => test123#example.com
[1] => lol123#example.com
[2] => haha#example.com
[3] => blahblah#example.com
)
//first name
Array
(
[0] => Bill
[1] => Jake
[2] => John
[3] => Bob
)
//last name
Array
(
[0] => Jones
[1] => Smith
[2] => Johnson
[3] => Bakers
)
I can get the one array easily like this: for example:
foreach ($emails as $email) {
echo $email;
}
That will echo out the emails. But I want to add $firstname and $lastname into it. for example, I want to echo:
test123#example.com Bill Jones
how can i do it?
foreach can assign a key and value if you use the appropriate syntax:
foreach ($emails as $key => $email) {
echo $email;
echo $firstnames[$key];
echo $lastnames[$key];
}
Next time, consult the manual: http://php.net/manual/en/control-structures.foreach.php as this is shown at the very top.
As Pyromonk pointed out, for is useful in situations where you have indexed arrays:
for ($i = 0, $n = count($emails); $i < $n; $i++) {
echo $emails[$i];
echo $firstnames[$i];
echo $lastnames[$i];
}
I am having a terrible time getting this to work I have been struggling with it for a couple hours now. Can someone please help me? I have included a fiddle.
I believe my problem is in this string:
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
Basically I have the following multidimensional array:
[sales] => Array
(
[FirstName] => Array
(
[0] => salesFirst1
[1] => salesFirst2
)
[LastName] => Array
(
[0] => salesLast1
[1] => salesLast2
)
)
[decisionmaker] => Array
(
[FirstName] => Array
(
[0] => dmFirst1
[1] => dmFirst2
)
[LastName] => Array
(
[0] => dmLast1
[1] => dmLast2
)
)
)
I need this to be reorganized like I did with the following array:
Array
(
[additionallocations0] => Array
(
[Address] => Address1
[State] => State1
)
[additionallocations1] => Array
(
[Address] => Address2
[State] => State2
)
)
Here is the original:
Array
(
[additionallocations] => Array
(
[Address] => Array
(
[0] => Address1
[1] => Address2
)
[State] => Array
(
[0] => State1
[1] => State2
)
)
This is how I reorganize the above array:
if(isset($_POST['additionallocations'])) {
$qty = count($_POST['additionallocations']["Address"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST['additionallocations'] as $param => $values)
{
$additional['additionallocations'.$l][$param] = $values[$l];
}
}
And this is what I am using for the sales and decisionmaker array. If you notice I have an array that contains sales and decisionmaker in it. I would like to be able to sort any future arrays by just adding its primary arrays name. I feel I am close to solving my problem but I can not get it to produce right.
$salesAndOwner = array(0 => "sales", 1 => "decisionmaker");
for($i = 0; $i < 2; $i++){
$qty = count($_POST[$salesAndOwner[$i]]["FirstName"]);
for ($l=0; $l<$qty; $l++)
{
foreach($_POST[$salesAndOwner[$i]] as $param => $values)
{
$$salesAndOwner[$i]["$salesAndOwner[$i]".$l] = $salesAndOwner[$i.$l][$param] = $values[$l];
}
}
}
In the above code I hard coded 'sales' into the variable I need it to make a variable name dynamically that contains the sales0 decisionmaker0 and sales1 decisionmaker1 arrays so $sales and $decisionmaker
I hope this makes sense please let me know if you need any more info
Let's break it down. Using friendly variable names and spacing will make your code a lot easier to read.
Remember. The syntax is for you to read and understand easily. (Not even just you, but maybe future developers after you!)
So you have an array of groups. Each group contains an array of attributes. Each attribute row contains a number of attribute values.
PHP's foreach is a fantastic way to iterate through this, because you will need to iterate through (and use) the index names of the arrays:
<?php
$new_array = array();
// For each group:
foreach($original_array as $group_name => $group) {
// $group_name = e.g 'sales'
// For each attribute in this group:
foreach($group as $attribute_name => $attributes) {
// $attribute_name = e.g. 'FirstName'
// For each attribute value in this attribute set.
foreach($attributes as $row_number => $attribute) {
// E.g. sales0
$row_key = $group_name . $row_number;
// if this is the first iteration, we need to declare the array.
if(!isset($new_array[$row_key])) {
$new_array[$row_key] = array();
}
// e.g. Array[sales0][FirstName]
$new_array[$row_key][$attribute_name] = $attribute;
}
}
}
?>
With this said, this sort of conversion may cause unexpected results without sufficient validation.
Make sure the input array is valid (e.g. each attribute group has the same number of rows per group) and you should be okay.
$salesAndOwner = array("sales", "decisionmaker");
$result = array();
foreach ($salesAndOwner as $key) {
$group = $_POST[$key];
$subkeys = array_keys($group);
$first_key = $subkeys[0];
foreach ($group[$first_key] as $i => $val) {
$prefix = $key . $i;
foreach ($subkeys as $subkey) {
if (!isset($result[$prefix])) {
$result[$prefix] = array();
}
$result[$prefix][$subkey] = $val;
}
}
}
DEMO
Try
$result =array();
foreach($arr as $key=>$val){
foreach($val as $key1=>$val1){
foreach($val1 as $key2=>$val2){
$result[$key.$key2][$key1] = $val2;
}
}
}
See demo here
I have this function :
function userKids(mysqli $Con, $Parent) {
$stmt = $Con->prepare('SELECT KidsName, KidsAge, KidsGender FROM Kids WHERE Parent = ?');
$stmt->bind_param('s', $Username);
$stmt->execute();
$Kid = null;
$Kids = array();
$stmt->bind_result($Kid, $KidsAge, $KidsGender);
while($stmt->fetch()) {
$Kids[] = $Kid;
}
return $Kids;
}
currently my WHILE loop produce array like this :
Array ( [0] => john [1] => jane )
Now, how to produce multidimensional array so I can get the Age and Gender as well, like this :
Array
(
[john] => Array
(
[0] => 3
[1] => male
)
[jane] => Array
(
[0] => 2
[1] => female
)
)
Change the line:
$Kids[] = $Kid;
To:
$Kids[$Kid] = array($KidsAge, $KidsGender);
I recommend that you use an associative array for the second dimension as well. So:
$Kids[$Kid] = array('age' => $KidsAge, 'gender' => $KidsGender);
replace the end of your code by:
$stmt->bind_result($KidName, $KidAge, $KidGender);
while($stmt->fetch()) {
$Kids[$KidName] = array($KidAge,$KidGender);
}
return $Kids;
In MySQL I can SELECT a value from one column of a row WHERE one or more columns have a specified value:
SELECT name FROM table WHERE birthyear = '1965' AND birthplace = 'Vancouver'
Now I have a multidimensional PHP_array (not a mySQL database), and I would like to extract the name from the row for a given birthyear and birthplace in a similar manner. This is the array:
$example = Array
(
[0] => Array
(
[0] => 1965
[1] => Bob
[2] => Vancouver
)
[1] => Array
(
[0] => 1973
[1] => John
[2] => Vancouver
)
[2] => Array
(
[0] => 1965
[1] => Paul
[2] => Houston
)
)
It seems to me that for each WHERE-condition I would need one loop in PHP. If you assume that I need to match several columns (birthday, birthplace, sex, occupation etc.), you'll understand how this slows down the execution over an array with thousands of entries.
How can I do this with the least number of loops?
array_filter($example,function($v) { return $v[0] == 1982; });
This function will do what you are looking for:
function getNameByYear($year, array $array) {
$name = false;
foreach ($array as $a) {
if ($a[0] == $year) {
$name = $a[1];
break;
}
}
return $name;
}
Usage:
$example; // your array
$n = getNameByYear(1965, $array); // Bob
$n = getNameByYear(1973, $array); // John
$n = getNameByYear(1982, $array); // Paul
$n = getNameByYear('1965', $array); // Bob
$n = getNameByYear('1973', $array); // John
$n = getNameByYear('1982', $array); // Paul
$n = getNameByYear('wrong', $array); // false
$n = getNameByYear(2035, $array); // false
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'];
}
}