duplicate rows from foreach using php - php

i have output from query
object(stdClass)#14 (6) {
["aid"]=>
string(2) "11"
["bid"]=>
string(2) "34"
["colorname"]=>
string(6) "Silver"
["colorgroupname"]=>
string(15) "LIGHT AQUA OPAL"
["colorcode"]=>
string(3) "6M8"
["brand"]=>
string(6) "Car"
}
but after loop in foreach
complite code what i use and i use var_dump to display output i get one rows but after loop i get 6 duplicate rows.
function ViewDBGridColorfinder($header,$DBG_control,$parameters)
{
$rows = $this->select_join_by(index_join_ColorFinder,TBL_COLOR,tbl_join_ColorFinder,where_by,order_by_dbgrid,$parameters);
$table = new Generator_Table($header);
//var_dump($rows);
if (is_array($rows) || is_object($rows))
{
foreach($rows as $val)
{
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
}
}
$DBGrid_data = $table->generate();
return $DBGrid_data;
}
the result to be duplicate.
where is the error?

I think this sholud only do for you
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
Remove foreach as.

Replace all $rows with $val in foreach loop

You used the variable $rows itself instead of $val. Update the code like this:
foreach($rows as $val)
{
$DetailColor = ''.$val->colorname.'';
$table->addCell($DetailColor);
$table->addCell($val->colorcode);
$table->addCell($val->brand);
$table->addCell($val->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$val->aid.")",$DBG_control));
}

Your $row is an object. So you don't really need to forloop inside the object. The reason why your getting 6 records is because there are six elements inside your object.
Count this and see, There are 6 elements(aid,bid,colorname,colorgroupname,colorcode,brand):
object(stdClass)#14 (6) {
["aid"]=>
string(2) "11"
["bid"]=>
string(2) "34"
["colorname"]=>
string(6) "Silver"
["colorgroupname"]=>
string(15) "LIGHT AQUA OPAL"
["colorcode"]=>
string(3) "6M8"
["brand"]=>
string(6) "Car"
}
So for each element, it will add the cell.In PHP you can use the -> to access the elements inside the object. Modify the code this way:
if (is_array($rows) || is_object($rows))
{
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
}

Related

add 2D array key php [duplicate]

This question already has answers here:
PHP foreach change original array values [duplicate]
(5 answers)
Closed 5 years ago.
I tried to add a key and its in a 2D array using a foreach. The problem is that this key isn't "saved". As soon as I try to look the first array, the key I added disappeared.
There is the code :
$Etapes=$this::getEtapes();
foreach($Etapes as $Etape){
$req = $this::getSuiviEtapes();
$Etape['Nom_Suivi'] = $req[0]['Nom_Suivi'];
if($Etape['ID_Etat_Etape']=="22")
{
var_dump($Etape);
var_dump($Etapes);
$this->Etapes=$Etapes;
var_dump($this->Etapes);
}
}
And there is the return
array(3) {
["ID_Etat_Etape"]=>
string(2) "22"
["Nom"]=>
string(36) "Comparatif"
["Nom_Suivi"]=>
string(8) "En_cours"
}
array(2) {
[0]=>
array(2) {
["ID_Etat_Etape"]=>
string(2) "21"
["Nom"]=>
string(12) "Etude"
}
[1]=>
array(2) {
["ID_Etat_Etape"]=>
string(2) "22"
["Nom"]=>
string(36) "Comparatif"
}
}
array(2) {
[0]=>
array(2) {
["ID_Etat_Etape"]=>
string(2) "21"
["Nom"]=>
string(12) "Etude"
}
[1]=>
array(2) {
["ID_Etat_Etape"]=>
string(2) "22"
["Nom"]=>
string(36) "Comparatif"
}
}
as you can see, the "Nom_Suivi" key do not appear in the second and third array.
I don't know if my issue is clear enough. Ask if it isn't.
Thank you for helping.
If you want to modify array you are iterating over with foreach, you either have to use reference - foreach($Etapes as &$Etape) or (prefered way) change the value by using the original array variable and key:
foreach($Etapes as $key => $Etape){
...
$Etapes[$key]['Nom_Suivi'] = $req[0]['Nom_Suivi'];
...
}
Try using
foreach ($fields as $key => $field)
Use the key
Check out this Duplicate of this question

Create nested pages-list from MySQL database using recursion with fixed ordering

I am trying to create a nested pages-list from data stored in the MySQL database.
I try to do this because users can order the pages (using JS-script nestedSortable) in the way they want and from that array, I can then create a menu with the items in the right order.
My pages have the following data stored:
page_id
parent_page_id
ordering
site_id
title
I retrieve the following from the database:
SELECT * FROM `pages` WHERE site_id = '".$iSite_id."' ORDER BY parent_page_id, ordering ASC;
If a page does not have a parent, the parent_page_id is 0.
So far so good, but I have a lot of problems understanding how a recursive function works, and because the amount of levels is (theoretically) endless, I can't work around creating this function.
This is what I have so far:
$aPagesMenu = $oPage_controller->return_pages_menu($iSite_id);
function create_menu_recursive($aPagesMenu) {
foreach($aPagesMenu as $aPage) {
if($aPage['parent_page_id']){
$aMenu[$aPage['parent_page_id']][$aPage['page_id']] = $aPage['title'];
//Recursive function call here?
} else {
$aMenu[$aPage['page_id']] = $aPage['title'];
}
return $aMenu;
}
$aRecursiveMenu = create_menu_recursive($aPagesMenu);
I get stuck at trying to understand how the recursive function returns its content into the array of the first level?
How can I understand this and correctly nest one level into another?
I really wish to understand this, because it gives me a lot of delay and issues. Any help is welcome!
EDIT
Some data retreived from database:
array(6) {
[0]=>
array(4) {
["page_id"]=>
string(3) "274"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[1]=>
array(4) {
["page_id"]=>
string(3) "278"
["parent_page_id"]=>
string(1) "0"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[2]=>
array(4) {
["page_id"]=>
string(3) "273"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[3]=>
array(4) {
["page_id"]=>
string(3) "275"
["parent_page_id"]=>
string(3) "274"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
[4]=>
array(4) {
["page_id"]=>
string(3) "276"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "0"
["page_description"]=>
NULL
}
[5]=>
array(4) {
["page_id"]=>
string(3) "277"
["parent_page_id"]=>
string(3) "275"
["menu_ordering"]=>
string(1) "1"
["page_description"]=>
NULL
}
}
This data should then be converted to:
273
--> 275
--> 274
--> 276
--> 277
278
etc..
I have searched through older posts on stackoverflow and I think I have found what I was looking for: PHP Building Recursive Array from List
I have used the following code as recursive function:
private function buildTree($itemList, $parentId) {
// return an array of items with parent = $parentId
$result = array();
foreach ($itemList as $item) {
if ($item['parent_page_id'] == $parentId) {
$newItem = $item;
$newItem['children'] = $this->buildTree($itemList, $newItem['page_id']);
$result[] = $newItem;
}
}
if (count($result) > 0) return $result;
return null;
}
I then called this function with the array I've got from the database:
buildTree($aPages, 0);
Which gave me the array :D

Trouble getting data from an array in PHP

I've got this array:
array(1) {
["sensory-evaluation"]=> array(6) {
["name"]=> string(18) "Sensory Evaluation"
["value"]=> string(43) "10/22/2015 at 6:00pm | 11/25/2015 at 6:00pm"
["position"]=> string(1) "3"
["is_visible"]=> int(1)
["is_variation"]=> int(1)
["is_taxonomy"]=> int(0)
}
}
I need to be able to get the data from ["value"]. If I do $arr["sensory-evaluation"]["value"] I can get it but the problem is ["sensory-evaluation"] will be different for each element in my array so I need a way to abstract that part but I haven't been able to figure it out.
If you have only one item in the array as you show then:
echo current($arr)['value'];
If you don't know if it exists:
if(isset(current($arr)['value'])) {
echo current($arr)['value'];
}
You could also do:
echo array_values($arr)[0]['value'];
why not use a for each
function getValue($arr){
foreach ($arr as $key => $value) {
var $subArray=$arr[$key];
if( array_key_exists ('value' ,$subArray))
return $arr[$key]['value'];
}
}

looking for Eloquent [Capsule::select] return indexed array (not just order numbers)

I'm exceuting this query....
use Illuminate\Database\Capsule\Manager as Capsule;
[...]
$sql = "SELECT
blabla";
$clients = Capsule::select($sql);
dd($clients);
From this i get something like this:
[0]=>
array(4) {
["house_rec_by_class"]=>
string(8) "-1250.00"
["client_name"]=>
string(11) "lalala"
["client_id"]=>
string(19) "800001D1-14037201481"
["contract_stage"]=>
string(4) "Live"
}
[1]=>
array(4) {
["house_rec_by_class"]=>
string(7) "-250.00"
["client_name"]=>
string(15) "lolololo"
["client_id"]=>
string(19) "80000180-13939692362"
["contract_stage"]=>
string(4) "Live"
}
Now what i'd like is to get this same array, with the [client_id] in the keys, instead of just consecutive numbers... like
["800001D1-14037201481"]=> ['client_name' => 'lalalala', '...'],
["80000180-13939692362"]=> ['client_name' => 'lolololo', '...']
I know i can re-loop the array and assign the keys, just was curious if there is a better way..
Thanks..!
You need something like thit:
foreach ($clients as $elem) {
$id = $elem['client_id'];
$newClients[$id]['client_name'] = $elem['client_name'];
$newClients[$id]['contract_stage'] = $elem['contract_stage'];
// etc
}
You now have a new Array $newClients as expected. I would suggest you to use isset to check if every element exists.

how to use foreach with array_key_exists function

I am trying to loop around an array of return values from a 'POST form' and to then place those values into a database.
the problem that I have is to determine the best way to loop around those values. I tried using the array_key_exists(). but it appears that this function only works with an If clause.
I am working in ZendFrameWork 1.
I enclose my code below and would really appreciate any help and advice.
foreach(array_key_exists('id', $ReturnedPostvalues))
$product = EP3D::getSource('EP3D/Products')->retrieve($productId);
{
$product->quantity = $ReturnedPostvalues['quantity'];
$product->price = $ReturnedPostvalues['price'];
$product->rrp = $ReturnedPostvalues['rrp'];
$product->save();
}
}
the var_dumped array values returned from the post
array(6) {
["quantity"]=>
string(3) "222"
["price"]=>
string(3) "220"
["rrp"]=>
string(2) "22"
["sampleId"]=>
string(5) "42960"
["id"]=>
string(1) "5"
["delete"]=>
string(1) "0"
}
[6]=>
array(7) {
["quantity"]=>
string(4) "7777"
["price"]=>
string(4) "2022"
["rrp"]=>
string(2) "22"
["sampleId"]=>
string(5) "42960"
["id"]=>
string(1) "6"
["delete"]=>
string(1) "0"
}
I basically need to loop around this array and input the data into the database.
Maybe this is what you want:
foreach($ReturnedPostvalues as $value) {
if (array_key_exists('id', $value)) {
$product = EP3D::getSource('EP3D/Products')->retrieve($value['id']);
$product->quantity = $value['quantity'];
$product->price = $value['price'];
$product->rrp = $value['rrp'];
$product->save();
}
}
You need to refresh your understanding of multi-dimensional arrays. Your problem is that you seemed to confuse accessing the top-level array and accessing the sub-arrays.

Categories