Can someone help me on how to implement a nested while loop in PHP?
Please give some example it will be highly appreciated. I am getting problem in internal while:
while ($record = db_fetch_object($username))
{
$userArray[] = $record->uid; //print "waheed----";
while($recordfile = db_fetch_Object($userfile))
{
print "waheed";
$userArray [$record->uid][] = $recordfile->fid;
}
}
while($condition1)
{
while($condition2)
{
// statements
}
}
EDIT
I guess this is the problem with the while loop of AAMIR:
$recordfile = db_fetch_Object($userfile)
the word object has Capital case 'O'. Make it small.
Related
I'm working with data from Formstack's REST API. Everything is in XML format. I wrote some PHP to process it, and for some reason when I echo $valueVar in a foreach loop only the value from the first entry is returning for each of the three entries. I really don't know why the string isn't getting replaced. Could someone please shed some light on what I'm doing wrong.
Thank you!
PHP Output
Formstack API XML Output
foreach($xml->submissions->submission as $submission) {
foreach($xml->submissions->submission->data->XML_Serializer_Tag as $serializer) {
$fieldeVar = (string)$serializer->field;
$valueVar = (string)$serializer->value;
if ($fieldeVar=="95733876") {
echo $valueVar;
break;
}
}
}
I think this is a simple case of your 2 loops clobbering each other. Notice how you're defining the inner loop as foreach($xml->submissions->submission->.... That will always grab the first instance. It should be using $submission which your outer loop is setting up for you.
Just change
foreach($xml->submissions->submission as $submission) {
foreach($xml->submissions->submission->data->XML_Serializer_Tag as $serializer) {
to this
foreach ($xml->submissions->submission as $submission) {
foreach ($submission->data->XML_Serializer_Tag as $serializer) {
Output
prefix = Dr first = Argnes last = Acmefirst = Bobby last =
Leamalotfirst = Tina last = Students
I have a JSON file with around 30 sub sections. Each subsection will be different. I wanted to convert the data inside it into a format i wanted. The code works fine. But i feel its not optimized 100%.
Client1Insurance, Client2Insurance, ClientFInsurance, FamilyInsurance, Client1Pension, Client2Pension, ClientFPension, FamilyPension.
Above is an example of how this JSON would look like. All above are arrays which have sub arrays inside them. There are around 30 arrays like this.
foreach ($json as $item) {
if (strpos($crmMapKey, "Insurance")) {
$returnArray[] = $this->handleInsurance($item);
} elseif (strpos($crmMapKey, "Pension")) {
$returnArray[] = $this->handlePension($item);
} ... continues the comparison till the json ends
}
I need a way to avoid this long if else comparions which I am not proud of. Will someone be able to suggest a better way to do this?
Thanks.
If they are named the same as you show in your code, something containing Insurance will call handleInsurance, etc. then just get the term and use it in the method call:
preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$match[0]}($item);
If not then you can use a lookup array:
$lookup = ['Insurance' => 'doSomething', 'Pension' => 'doAnotherThing'];
preg_match('/Insurance|Pension/', $crmMapKey, $match);
$returnArray[] = $this->{'handle'.$lookup[$match[0]]}($item);
Or use the keys in the pattern so you only have to modify the array:
preg_match('/'.implode('|', array_keys($lookup)).'/', $crmMapKey, $match);
The switch I mentioned in a comment might not be the best but works:
switch(true) {
case strpos($crmMapKey, "Insurance") !== false;
$returnArray[] = $this->handleInsurance($item);
break;
case strpos($crmMapKey, "Pension") !== false;
$returnArray[] = $this->handlePension($item);
break;
//etc...
}
Another way would be to call variable based functions.
foreach ($json as $item) {
$returnArray[] = $crmMapKey($item);
}
function Client1Insurance($item) {
// Do something in here.
return $array;
}
function Client2Insurance($item) {
// Do something in here.
return $array;
}
Much more elegant way of doing things I feel.
I have 2 loops,
I would like that for each iteration of fighters2, $fighter1 also advance 1 element. Is is posible to do it with foreach????
foreach ($fighters1 as $fighter) {
foreach ($fighters2 as $fighter2) {
}
}
not sure if i understand the question correctly, but here is the answer to how i understood the question.
if your arrays are the same size you could do sth like this:
foreach($fighters1 as $index => $fighter) {
$fighter2 = $fighters2[$index];
//do what you need to do with $fighter and $fighter2
}
that is assuming both arrays are same size and have numeric indexes
Maybe using next() might help you.
foreach ($fighters1 as $fighter) {
$nextFighter1 = next($fighters1);
foreach ($fighters2 as $fighter2) {
//do whatever you need
}
}
next() reference
Bye!
https://graph.facebook.com/search?q=tom&type=user&access_token=2227470867|2.AQD2FG3bzBMEiDV3.3600.1307905200.0-100001799728875|LowLfLcqSZ9YKujFEpIrlFNVZPQ
how to avoid repeat name in facebook people search? in the json code, there have 2 Thomas Lee. Thanks.
foreach ($status_list['data'] as $data) {
echo $data['name']; // not print the same name.
}
$names = Array();
foreach ($status_list['data'] as $data) {
$names[] = $data['name'];
}
$names = array_unique($names); // not print the same name.
foreach ($names as $name) {
echo $name;
}
Here's a fast mashup of how you remove duplicates:
<?php
function existsInArray($list, $key, $value){
foreach($list as $lkey => $lvalue){
if($lvalue[$key] == $value){
return true;
}
}
return false;
}
$sortedUsers = array();
foreach($status_list['data'] as $data){
if(!existsInArray($sortedUsers, "id", $data["id"])){
$sortedUsers[] = $data;
}
}
This will go through the array och users, check if each item exist with the same id in the sorted array. If it doesn't exist, it will be added to the sorted array. Then you have $sortedUsers which doesn't contain any duplicates.
Note: However, this is just proof of concept code. So there are probably a lot of performance optimization that could be done. Also, there are probably some built in functionality to which can do this with less user defined code. Why I showed this is to just explain the process.
Edit: Since this answer got accepted I feel obligated to show something which is a little more high quality than proof of concept code. Also because it got mentioned in the comments that it was inefficient.
So here's easy fix to make this much faster:
$sortedUsers = array();
foreach($status_list['data'] as $data){
$sortedUsers[$data["id"]] = $data;
}
This way it will just overwrite the duplicates and will take away the whole process of comparing each item. In worst case this will be O(n) where as the proof of concept code was O(n ^ (n / 2)) in worst case.
I looking for another samples of php foreach code that similar to the code as following:
foreach ($this->ask->post['books'] as $book) {
if ($book['qty']) {
$this->goto->add($book['book_id'], $book['qty'], (isset($book['opt'])) ? $book['opt'] : NULL);
}
}
I just want to save it as my collection, so, is there another samples of php foreach that You may know? let me know it. Thanks
Maybe this example can help you:
foreach($myArrayOfObject as $key=>$object) {
if($object->aPropertyOfMyObject) {
// do something...
}
}
You can also have a look to http://php.net/manual/en/control-structures.foreach.php
Do you specifically need foreach?
You can also use this:
<?php
$array = array(); // Imagine a filled array
array $max = count($array);
for($i=0;$i<$max;$i++) {
// Loop over the array
echo $array[$i]['name_of_key'];
}
?>