I have this PHP foreach loop:
foreach($emails_list as $email)
but i want to do something like
foreach($emails_list as $email and $forename_list as $forename)
my code above the foreach loop is:
$sql2="SELECT * from contacts where company_sequence = '".$customersequence."' and contactstatus = '' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
while($result2=mysql_fetch_array($rs2))
{
$emails_list[] = $result2["email"];
}
si i want to be able to include $result["forename"]; within the loop too
will the above work to make 2 loops?
Not sure if understand, but try use for instead:
$emails_list = array("01#gmail.com", "02#gmail.com", "03#gmail.com", "04#gmail.com");
$forename_list = ("01 something", "02 something", "03 something", "04 something");
if($emails_list == $forename_list){
$count = count($emails_list);
for($i=0;$i<$count;$i++){
echo 'Email: '.$emails_list[$i].', Name: '.$forename_list[$i];
}
} else { echo 'Troubles'; }
there is no way to do this in foreach in a one statment
for this use for loop like
for ($i=0;$i<=count($emails_list); $i++) {
echo $emails_list[$i];
echo $forename_list[$i];
}
All the examples listed with a basic for loop will work fine for numeric arrays, however what about associative arrays?
The best way to do this would be something like the following:
$arr_1 = array( 'foo'=>'bar', 'fizz'=>'bang' );
$arr_2 = array( 'hello'=>1, 2=>'world' );
$array_size = count( $arr_1 ); // NOTE: This assumes the arrays are of the same size.
// Reset the internal array pointers
reset( $arr_1 );
reset( $arr_2 );
for ($i = 0; $i < $array_size; $i++ ) {
$first_array_element = current( $arr_1 );
$second_array_element = current( $arr_2 );
// code here
next( $arr_1 );
next( $arr_2 );
}
This will handle both associative and numeric arrays.
Related
I have an array
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
I want to convert this to
$multiarr=array(
[0]=>array(
['id']=>1,
['name']=>'abc'),
[1]=>array(
['id']=>2,
['name']=>'xyz'),
[2]=>array(
['id']=>3,
['name']=>'pqr')
);
id is key and the name is the value of the first array
how can I implement this optimistically
I have done this
$keys=array_keys($arr);
$values=array_values($arr) ;
$multiarr=array();
for($i=0; $i<count($keys); $i++)
{
$multiarr[$i]['id']=$keys[$i];
$multiarr[$i]['name']=$values[$i];
}
Thanks.
Should really be trying this yourself mate, but this should help:
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
$MultiArr = array();
$i = 0;
foreach($arr as $ID=>$Name){
$MultiArr[$i]['id'] = $ID;
$MultiArr[$i]['name'] = $Name;
$i++;
}
print_r($MultiArr);
I am trying to create 2 new arrays out of one existing array ($array), using the following "foreach" loop. However I am not sure it is correct:
$emails = array();
$numbers = array();
while($array){
$entry = $array['entry1'];
$number = number($entry);
if(isset($number) && (strlen($number) > 9)){
$numbers[] = array('entry1' => $entry, 'number' => $number);
}
else{
$email = email($entry);
$emails[] = array('entry1' => $entry, 'email' => $email);
}
}
should the internal arrays have []?
do I even need to start the arrays outside of the while loop? or skip it?
is it better to use a foreach loop?
Update:
Okay, here is the original array: It is extracted from a mysql query, of sets of two numbers:
{('uid1','uid2'),('uid1','uid5'),('uid9','uid93'),....)
There might be other data in each row, but these are the only two data points that really matter.
What I am trying to do is for a specific user ($entry), create two separate arrays: of all the users that have numbers (that's a function we have), and all the rest - of their emails.
So the outcome will be 2 new arrays which will look like this:
for a specific uid79887:
numbers array: {('uid8','xxx-xxxx-xxx'),('uid34','yyy-yyyy-yyy'),('uid654','vvv-vvvv-vvv')}
emails array: {('uid4','mmm#mmm.com'),('uid1','lll#lll.com'),('uid55554','ppp#ppp.com')}
Few things first:
It's good practice to initialize your variables, just do it (it has many positives).
What kind of test is while($array)? You should use foreach( $array as $entry) or while( count( $array)) if you're removing items from array.
Why are you testing isset( $number) when it's always set? It's initialized variable. You're probably checking null, so use !is_null() or ($number !== null). Even if it works it's misleading.
I guess your code should look like this:
$emails = array();
$numbers = array();
foreach( $array as $entry){
$entry = isset( $entry['entry1']) ? $entry['entry1'] : null;
$number = number( $entry);
if( strlen($number) > 9 ){ // If $number is empty it will have strlen < 1 .)
$numbers[] = array('entry1' => $entry, 'number' => $number);
} else {
$emails[] = array('entry1' => $entry, 'email' => email( $entry));
}
}
I guess this is what you are trying to acheive:
$emails = $numbers = Array();
foreach($array as $item) {
$e = $item['entry1'];
$number = number($e);
if(strlen($number) > 9) {
$numbers[] = Array('entry1' => $e, 'number' => $number);
}
else {
$email = email($entry);
$emails[] = Array('entry1' => $e, 'email' => $email);
}
}
in your code, while($array) do not loop on the array, it loop until $array == false
as $array do not change in your loop it will either never enter or the loop, or never exit
generally, using a foreach loop produce code easier to understand
Assuming this isn't some kind of homework assignment, why don't you do it this way:
$emails = array();
$numbers = array();
foreach( $array as $entry )
{
$number = number($entry);
if( $number && strlen($number) > 9 )
{
array_push($numbers, array('entry1' => $entry, 'number' => $number));
}
else
{
array_push($emails, array('entry1' => $entry, 'email' => email($entry)));
}
}
It is better to use built in functions that trying to roll your own. The foreach() function works very well.
I have a arrays like this.
$pahrmacyid=array(
"Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],
"IDQualifier"=>"D3"
)
)
);
$storename=array(
"StoreName"=>$_GET['storename']
);
$pharmacyaddress=array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
);
$communicationnumber=array(
"CommunicationNumbers"=>array(
"Communication"=>array(
"Number"=>$_GET['pCommunicationNumbers'],
"Qualifier"=>"TE"
)
)
);
I want to push this arrays into another array?Is it possible?
I need a result like this:
$result=array(
array("Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],"IDQualifier"=>"D3"
)
)
),
"StoreName"=>$_GET['storename'],array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
),
array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
)
)
It's simple since you have all the array's. Here are a couple of ways to merging all the array's into one multidimensional array.
Example 1:
$example1arr = array(
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 1: <pre>".print_r($example1arr,true)."</pre><br />\n";
Example 2:
$example2arr[] = $pahrmacyid;
$example2arr[] = $storename;
$example2arr[] = $pharmacyaddress;
$example2arr[] = $communicationnumber;
echo "Example 2: <pre>".print_r($example2arr,true)."</pre><br />\n";
Example 3:
$example3arr = Array();
array_push(
$example3arr,
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 3: <pre>".print_r($example3arr,true)."</pre><br />\n";
$result[] = $pahrmacyid;
And if you have multiple $pahrmacyid-arrays you can add it in a loop.
$result = array();
for($i = 0; $i < count($sourceArray); $i++)
{
$result[] = $sourceArray[$i];
}
$result[] = $pahrmacyid;
You may want to initilize it before with
$result = array();
And I didn't try but maybe the shortcut
$result = array($pahrmacyid);
works...
array_push($result, $pahrmacyid)
or
$result[] = $pahrmacyid
any of these two should do the trick
How can iterate with a while loop until array1 is empty.
So far based on several conditions I'm pushing elements from array1 to array2. But I want to iterate array1 until everything from array1 is in array2.
something like:
// or while everything from array1 is on array2
while(array1 is empty){
if(somecondition1)
array_push(array2,"Test");
unset(array1[$i]);
elseif(somecondition2)
array_push(array2,"Test");
unset(array1[$i]);
}
Any ideas will be appreciate it!
count() would work:
while(count(array1)){
if(somecondition1)
array_push(array2,"Test");
elseif(somecondition2)
array_push(array2,"Test");
}
or use do..until
do {
if(somecondition1)
array_push(array2,"Test");
elseif(somecondition2)
array_push(array2,"Test");
} until (count(array1) == 0)
Here's a test I did expanding upon your pseudo-code
$array1 = range( 1, 10 );
$array2 = array();
$i = 0;
while ( !empty( $array1 ) )
{
if ( $array1[$i] % 2 )
{
array_push( $array2, "Test Even" );
unset( $array1[$i] );
} else {
array_push( $array2, "Test Odd" );
unset( $array1[$i] );
}
$i++;
}
echo '<pre>';
print_r( $array1 );
print_r( $array2 );
I have a array of associative arrays
aa[] = ('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );
aa[] = ('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>3 );
aa[] = ('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>44 );
aa[] = ('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>45 );
aa[] = ('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>433 );
aa[] = ('Tires'=>23, 'Oil'=>33, 'Spark Plugs'=>44 );
Two Questions
How can I remove duplicates according tot he field 'Oil'
is there a array_unique which I can provide a callback which acts as a custom comparator?
How can I sort by a custom field 'Spark Plugs'
I don't know of a function you can use to do this. You will have to do a foreach over the values of the array and do the uniqueness checking manually.
Use the usort() function and provide a custom comparator.
Instead of manually going and doing the usual duplicate checking, I did this
$aa2 = array()
foeach($aa as $key => $value) {
$aa2[$value['Oil']] = $value;
}
$aa = $aa2;
Then sorting was done by the key...
For question 1, I think array_filter is what you need.
And, like Brian says, usort for your second question.
The issue with remove dupes this way, is how do you determine which values remain, since you're talking about partial uniqueness.
This solution below just keeps the first to appear in index-order. It's not exactly elegant, but it works.
<?php
$aa = array();
$aa[] = array('Tires'=>100, 'Oil'=>10, 'Spark Plugs'=>4 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>3 );
$aa[] = array('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>44 );
$aa[] = array('Tires'=>454, 'Oil'=>43, 'Spark Plugs'=>45 );
$aa[] = array('Tires'=>34, 'Oil'=>55, 'Spark Plugs'=>433 );
$aa[] = array('Tires'=>23, 'Oil'=>33, 'Spark Plugs'=>44 );
echo '<pre>';
print_r( arrayUniqeBySubKey( $aa, 'Oil' ) );
echo '</pre>';
function arrayUniqeBySubKey( $array, $key )
{
$indexAggregates = array();
foreach ( $array as $idx => $subArray )
{
$indexAggregates[$subArray[$key]][] = $idx;
}
foreach ( $indexAggregates as $originalIndexes )
{
$numOriginals = count( $originalIndexes );
if ( 1 == $numOriginals )
{
continue;
}
for ( $i = 1; $i < $numOriginals; $i++ )
{
unset( $array[$originalIndexes[$i]] );
}
}
return $array;
}
You can indeed use array_filter for filtering your data:
$bb = array_filter($aa, function($item) {
static $tmp = array();
if ($filter = !in_array($item['Oil'], $tmp)) {
$tmp[] = $item['Oil'];
}
return $filter;
});
This uses a static variable inside the function to "remember" the Oil already returned. This works, because $tmp is used only during the execution of array_filter. If you wrap this into a function and call it multiple times for example, $tmp will always be an empty array for the first call of the function provided to array_filter.
The second task, the sorting, can be done using usort with a custom sorting function:
usort($bb, function($a, $b) {
return ($a['Spark Plugs'] > $b['Spark Plugs']
? 1
: -1);
});