PHP - associative array - blank row being added - php

I am trying to build Dynamic UI by getting data from DB using CodeIgniter but facing problem in constructing array.
Requirement:
Get parent menu items in an array. Then get child item corresponding to each parent item.
Code to get data for parent element::
$data['menu'] = $this->Menu->get_admin_menu_data();
This gives me 3 records
echo "before loop menu" . count($data['menu']) . "</br>"; //prints 3
Now I run a foreach loop for each parent item to retrieve it's child item
foreach($data['menu'] as $menu){
$data['menu']['menu_item'] = $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
echo "inside loop menu " . count($data['menu']) . "</br>"; //prints 4
}
As soon as I do this the count of menu increases to 4 resulting in error in UI.
I am new to PHP so now sure what is the best way to create a structure to hold this type of data.
Please help!!!!

If $data['menu'] contains 3 key/value pairs, but $data['menu']['menu_item'] is not set, your statement
$data['menu']['menu_item']
= $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
sets just this.
Thus count( $data['menu'] ) returns 4 elements afterwards - including the newly added 'menu_item' key.

I don't know CodeIgniter, but overwriting a static variable
$data['menu']['menu_item'] = "someting"
never makes sense. Where do you really want to store the result of
$this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
? You can and should check the content of a variable using var_dump.

Related

print mongodb array field values of document using php

Hi I have a mongodb database where i store products and each product doc is like below :
Using php I want to print all instances of "user" from the "comments" array
What I tried :
$collection=$db->products;
$itemID = $_POST['itemID'];
$cursor = $collection->findOne(["id"=>$itemID]); //find an item
//print all user names who commented on item
foreach($cursor['comments'] as $c){
echo "<p> User : ".$c["user"]." </p>";
}
";
exit();
And I get :
Warning: Invalid argument supplied for foreach()
This is the first time I do this so I would appreciate your help
From the findOne() docs: As opposed to MongoCollection::find(), this method will return only the first result from the result set, and not a MongoCursor that can be iterated over.
( you need to use find().limit(1) to fetch single document if you want to iterate with forEach construction or you must remove the forEach method to be able to use the findOne() )
If you need to iterate over the comments arrray elements and there is nothing found in the database it will be a problem , so you need to check first if the comments exist ...
Before the end line there is ' "; ' that seems to need to be removed ...

PHP array insertions do not work as expected

I am trying to insert some items (suppose n items), which are all different from each other, to an array. Somehow, the final array consists of n items, Which all are the same item: the last inserted item.
This is my code:
$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
$searchResultJSon->dealid = $searchResultItem['id'];
$searchResultJSon->title = $searchResultItem['title'];
//$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
//$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
$searchResults_data[] = $searchResultJSon;
}
So I tried to figure out why is that.. using DEBUGGING1,DEBUGGING2 (in the client side, I get the messages sent by $from->send() and simply alert() them).
When alerting the DEBUGGING1 messages - I do see that all the items are correct and different from each other.
When alerting the DEBUGGING2 messages - the array duplicates the last inserted item each loop. So assume I insert n items, The array in the i-th loop will be: [item-i, item-i, item-i, ... item-i] instead of [item-1, item-2, item-3,...,item-i]
Your problem is that you're not creating a new object each time you go through the loop, so when you push $searchResultJSon into $searchResults_data you are pushing the same object, and the changes you make to it in the last iteration of the loop are reflected in all the values in $searchResults_data. You can work around that by creating a new object in each pass:
$searchResults_data = [];
foreach($allowSearch as $searchResultItem) {
$searchResultJSon = new StdClass();
$searchResultJSon->dealid = $searchResultItem['id'];
$searchResultJSon->title = $searchResultItem['title'];
//$from->send(json_encode($searchResultJSon)); --- DEBUGGING1 ---
//$from->send(json_encode($searchResults_data)); --- DEBUGGING2 ---
$searchResults_data[] = $searchResultJSon;
}

Store and check multiple $_SESSION

I have 3 objects with same variable but rendered with diferent values.
001 - Title one
002 - Title two
003 - Title three
I need to check on another block of page if this first three are the same. The only thing that comes to mind is store this variables in a $_SESSION. So far so good. The problem is that it only stores last value (obviously).
CODE
/* -- block one --*/
session_start();
$_SESSION['lasttitle'] = $item->getTitle;
echo $item->getTitle(); //rendering 1st object
echo $item->getTitle(); //rendering 2nd object
echo $item->getTitle(); //rendering 3rd object
/* -- block two --*/
session_start();
$last3 = $_SESSION['lasttitle'];
if($item->getTitle() != $last3) {
//don't render last 3
}
$_SESSION['lastTitles'][] = $item->getTitle();
$_SESSION['lastTitles'] = array_slice($_SESSION['lastTitles'], -3);
..
if (in_array($item->getTitle(), $_SESSION['lastTitles'])) ..
This stores an array of the last three titles, and checks whether a title is in this array.
Create multidimensional session:
$_SESSION['lasttitle'][$item->id] = $item->getTitle();
$_SESSION['lasttitle'][$item2->id] = $item2->getTitle();
$_SESSION['lasttitle'][$item3->id] = $item3->getTitle();
And check if that element is in array:
$total = 0;
foreach ($items as $item) {
if (isset($_SESSION['lasttitle'][$item->id])) {
$total++;
}
}
if ($total == 3) {
// Do something, it's all 3 titles in session!
}
I know it may be better solution, but I don't understand full algorithm. Also, to compare some arrays, you can use array_diff_assoc()
I think storing data as array in session might help you. Simply gather all titles you need in an array and put it into $_SESSION (instead of one variable). One the next page you will be able to analyze data you have and choose variables you need.

Object Loop Not Working as Expected

I will be honest, I have just started learning objects and I am stuck.
I want to loop through an array of objects and display the name and description for each. But either nothing is displayed or it displays all the names first and then all the descriptions.
I am pulling the information from an API into the object:
// get tasks
foreach($tasksList->items as $task_details) {
$tasks_name[$task_details->id]=$task_details->name;
$tasks_desc[$task_details->id]=$task_details->description;
$tasks_details[$task_details->id]=$task_details->id;
$tasks_progress[$task_details->id]=$task_details->progress;
}
foreach($tasks_name as $taskid=>$my_task_name) {
echo "Task_Name: " . $my_task_name . "</br>";
$task_id = $task_details->id;
foreach($tasks_desc as $taskid1=>$my_task_desc) {
if($taskid==$task_details->id) {
echo "Task_Desc: " . $my_task_desc . "</br>";
}
}
}
Now what I don't understand is: inside the first foreach loop it is like a while loop while i=0, it checks $tasks_name[0], then $tasks_name[1] and so on.
However, I am not sure how to figure out what the id is in the current loop it is on, so I can tell it to only print the description of the current loop and not display all of them.
To be honest I am copying this from another example, but I don't quite understand it. I plan to study objects more, but this is holding me up on my current code:
foreach($tasks_desc as $taskid1=>$my_task_desc)
I understand it is looping through all the $tasks_desc and assigning the value to $my_task_desc but what is the signifigance of $taskid?
Sorry for the newbie questions. :)
This is poorly written. I would move on to another tutorial if it's a tutorial. Either that or the line that task_id is used was left out.
Anyway, tasks_name is an array of tasks indexed by the ID. So the outer loop in the second block loops over the keys/values of that array (the ID is the key, taskid. It was assigned by $task_details->id in the first loop above).
The second loop goes over all of the tasks again, but this time by description task_desc instead of by name. It's trying to find the task_desc with an ID that matches the ID of the task_name before (which would make it the same task).
That's unnecessary, though, because you could just store all of the entries (name, desc, etc.) in one array indexed by the ID instead of storing each in their own array:
(this is the first loop):
foreach($tasksList->items as $task_details) {
$all_tasks[$task_details->id]['name'] = $task_details->name;
$all_tasks[$task_details->id]['desc'] =$task_details->description;
// Don't need the ID again; it's the key
$all_tasks[$task_details->id]['progress'] = $task_details->progress;
}
However, you don't even need to do that, because you can just iterate over tasksList->items when you need to.
There's no need for two loops. To display name and description for each object, one loop is enough:
foreach($tasksList->items as $task_details) {
echo 'name: ', htmlspecialchars($task_details->name);
echo ', description: ', htmlspeciachars($task_details->description);
}
(I also don't understand why you want to store every object field in its own array first?)

Weird Return Value Logic Error from PHP Recursion

I need to write a recursive function to search through a set of parent and children link headers, then get the names of embedded key values per header. Ex. Clothing->Men->Shoes. Now, each category has an unknown number of values attached to them. I have a function that can successfully echo all of these values recursively through the parents. But when I try to get the return value from the function, it's missing some, and I can't understand why : /.
Code is below
public function getFamilies($cat){
$objCurrentCategory = Category::Load($cat); // creates a QCodo object of the passed category ID.
$str_Query = "SELECT DISTINCT p.family
FROM xlsws_product p, xlsws_product_category_assn pc
WHERE p.rowid=pc.product_id
AND pc.category_id=".$cat; // sql query to retrieve all Families relating to this category.
$objFamilyDb = Family::GetDatabase(); // retrieves the QCodo database object for Family to execute queries against.
$objFamilies = Family::InstantiateDbResult($objFamilyDb->Query($str_Query)); // executes the query and saves the result.
foreach($objFamilies as $family){ // for each family returned, get the family name and add it to the array of names.
if ($family->Family !== ""){
$families [] = $family->Family;
}
}
if ($objCurrentCategory->ChildCount > 0){ // if current category has children, create a list of all children rowids.
$str_Query = "SELECT rowid FROM xlsws_category
WHERE parent=".$objCurrentCategory->Rowid; // query to get all children of the category.
$objChildCategoriesDb = Category::GetDatabase(); // retrieves the QCodo database object for Category to execute queries against.
$objChildCategories = Category::InstantiateDbResult($objChildCategoriesDb->Query($str_Query)); // executes the query and saves the result.
foreach($objChildCategories as $child){ // passes through the children to get their families.
//$families [] = KG::getFamilies($child->Rowid);
$childFam = KG::getFamilies($child->Rowid);
}
}
$compiled = KG::compileFamilies($childFam); // helper function, not important.
foreach($compiled as $compile){
$families[] = $compile;
}
foreach($families as $familyt){ // this echo statement correctly displays all names.
//echo ":".$familyt."<br />";
}
return $families;
}
So this displays all the names through echo to the screen during the functions run, and the array WITHIN the function can be echo'd to the screen as well. But when I try to return all of the names from returned result in another page, I'm missing a bunch of names.
EDIT It looks like the $families variable is not persisting through each recursive call to getFamilies, and is only returning the children at the end, instead of the children and all their parents.
Fixed. problem was I was trying to clean up the array in the same recursive statement and it was throwing everything off since the cleaning "helper method" was being returned and not the full associative array of families. Sigh # me for being oblivious.

Categories