Assign value to array in for loop - php

I know init php array method is
$a=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
but i must assign in two dim array, such data is
[0]=> array(6) { ["id"]=> string(1) "2" ["menu_name"]=> string(12) "小吃菜單" ["button_pic_save_path"]=> string(40) "/images/left_button/menu/normal_menu.gif" ["cover_button_pic_save_path"]=> string(46) "/images/left_button/menu/normal_menu_cover.gif" ["order_number"]=> string(1) "0" ["modify_time"]=> string(19) "2013-04-07 09:37:43" } }
[1]=> array(6) { ["id"]=> string(1) "3" ["menu_name"]=> string(12) "小吃菜單" ["button_pic_save_path"]=> string(40) "/images/left_button/menu/normal_menu.gif" ["cover_button_pic_save_path"]=> string(46) "/images/left_button/menu/normal_menu_cover.gif" ["order_number"]=> string(1) "0" ["modify_time"]=> string(19) "2013-04-07 09:37:43" } }
now my Implement code as follow..
$query_menu_data = select_sql(QUERY_MENU_SQL_STR);
if(count($query_menu_data) >= 1)
{
$ary_menu[count($query_menu_data)];
for($loop_i = 0; $loop_i < count($query_menu_data); $loop_i++)
{
for($loop_j = 0; $loop_j < count($ARY_MENU_FIELD); $loop_j++)
{
// hash key
/*
$ary_menu[$loop_i] = array(
$ARY_MENU_FIELD[$loop_j] => $query_menu_data[$loop_i][$loop_j]
);
*/
$ary_menu[$loop_i] = array(
$ARY_MENU_FIELD[$loop_j] => $query_menu_data[$loop_i][$loop_j]
);
} // end loop j
} // end loop i
}
the result of array always save the last data, what method can I solve it.
Thank to every body, the solve method is in comment.

You need to initialize the menu entry. after doing that you need to fill each menu field for this menu.
code:
for($loop_i = 0; $loop_i < count($query_menu_data); $loop_i++)
{
$ary_menu[$loop_i] = array();
for($loop_j = 0; $loop_j < count($ARY_MENU_FIELD); $loop_j++)
{
// hash key
/*
$ary_menu[$loop_i] = array(
$ARY_MENU_FIELD[$loop_j] => $query_menu_data[$loop_i][$loop_j]
);
*/
$ary_menu[$loop_i][$ARY_MENU_FIELD[$loop_j]] = $query_menu_data[$loop_i][$loop_j];
} // end loop j
} // end loop i
i cant verify, if $query_menu_data has the correct data structure, but from your problem description, there should be no problem there.

It looks like your inner loop (loop_j) may never execute since you did not have $ARY_MENU_FIELD defined before you first execute it (and it is created/modified inside that loop). Is there other code you are not showing?

When you encounter problems with arrays only containing the "last" bit of data after a traversal/loop, you should assume that you are making an overwriting error somewhere.
Looking at your loop, the assignment comes in the second loop, with...
$ary_menu[$loop_i] = array(...
The = equals sign above should be the clue your looking for. You're assigning the index of $loop_i in the array $ary_menu over and over, every time the inner $loop_j for-loop runs. This is where the reassignment occurs.
Since I do not know exactly what you're trying to look for in a final array, I can only give an assumption on a solution. This might be doing something like...
$ary_menu[$loop_i][] = array(....)
What this will do is essentially make $ary_menu[$loop_i] an array of its own, appending the new value in each loop iteration. This will solve the problem of overwriting. But again, I'm not sure if that's what you're looking to do.

Related

multidimensional Array same value remove array

Hello everyone i'm struggling with a issue and couldn't really find my answer on the web.
Maybe i made a mistake than sorry but the answers i found where not exactly where i where searching for.
Here is my problem
["acList"]=>
array(356) {
[0]=>
array(36) {
["Id"]=>
int(434367)
["Rcvr"]=>
int(154)
["HasSig"]=>
bool(true)
["Sig"]=>
int(19)
["Icao"]=>
string(6) "06A0BF"
["Bad"]=>
bool(false)
["Reg"]=>
string(6) "A7-BDA"
["FSeen"]=>
string(21) "/Date(1509481499558)/"
}
[1]=>
array(43) {
["Id"]=>
int(3753696)
["Rcvr"]=>
int(149)
["HasSig"]=>
bool(true)
["Sig"]=>
int(23)
["Icao"]=>
string(6) "3946E0"
["Bad"]=>
bool(false)
["Reg"]=>
string(6) "A7-BDA"
["FSeen"]=>
string(21) "/Date(1509481476453)/"
}
I want that when "Reg" is the same that he removes only one of the same arrays (if possible based on FSeen).
I tried to make new array and combine them and i tried array_unique but that is not doing what i want sadly.
I hope someone can help me out with this.
Its not going to be the most efficient way, or great for large data sets, but this could work:
$aArray = array(array('id' => 1), array('id' => 2), array('id' => 1));
// create a tmp array to hold values we want to check
$aTmpArray = array();
// loop over the array
foreach ($aArray as $iPos => $aItem) {
if(!isset($aTmpArray[$aItem['id']])){
// if the item doesnt exist in tmp array, add it
$aTmpArray[$aItem['id']] = null;
}else{
// if the item exists, remove this entry from aArray
unset($aArray[$iPos]);
}
}
// set for gc
$aTmpArray = null;
It will preserve the first result and remove any subqiquent duplicates/occurances of id.

foreach results in endless loop

I have an array stored in $_SESSION:
var_dump($_SESSION['session_article']);
//result:
array(2) {
[0]=> array(2) {
["id"]=> string(1) "3"
["amount"]=> int(2)
}
[1]=> array(2) {
["id"]=> string(2) "13"
["amount"]=> int(1)
}
}
If I do:
for($artKey = 0;$artKey < count($_SESSION['session_article']);$artKey++){
$cartArt = $_SESSION['session_article'][$artKey];
//stuff that doesn't affect key or value
}
everything is fine ...but if I do:
foreach($_SESSION['session_article'] as $artKey => $cartArt){
//stuff that doesn't affect key or value
}
the page won't stop to load (infinite loading, like the foreach never terminates)
I would like to you know that the computer is not a dumb machine, so whenever you do not get the right result then its not the computers problem, it is in how you code.
So lets take a look at your code first you var_dump($_SESSION['session_article']) you got an array with two elements each being an associative array. Now observe that this is an array of arrays so you code in scenario 2 is wrong.
If it were to be just a single array say $myArray = ['Simon', 'Peter', 'You'] then this woul have worked fine (note I used the short array syntax here you can use array() if you prefer). But the problem is you have multidimensional Arrays so you could should be
foreach($_SESSION['session_article'], list($a,))
{
//stuffs here
}
or better walk through the $_SESSION['session_article'] as an associative array like so
$myArray = $_SESSION['session_article']
$field = count($myArray, COUNT_RECURSIVE - (int)2)
for ($record = 0; $record < $myArray.length; $record++) {
//record number
for ($field = 0; $field < $field ; $field++) {
//combine record and field here
}
}
Hope I could lend a helping hand?
Please checkout
http://php.net/manual/en/function.count.php
http://php.net/manual/en/control-structures.foreach.php
They really have a good doc, just take you time.

Dealing with php array whose content may or may not have another array

I am dealing with arrays whose structure is different depending on the number or items in the array.
For example, the following is the array with one item in it.
// Case #1
["Assignment"]=>
object(stdClass)#29 (9) {
["Id"]=> string(10) "1234567890"
..
}
However if there are more than 1 item in the array,
// Case #2
["Assignment"]=>
array(2) {
[0]=>
object(stdClass)#28 (9) {
["Id"]=> string(10) "1234567890"
..
}
[1]=>
object(stdClass)#28 (9) {
["Id"]=> string(10) "1234567890"
..
}
}
Notice that the contents are in another array for this. No matter of how many items there are, I want to access the Id. $array->Id will work for one case but won't work for the other with the error saying, Trying to get property of non-object.
I could come up with an inefficient way by counting the # of contents in the array like this:
// say the arrays above are declared as $assignment
if($numOfAssignment > 1) {
foreach($assignment as $key) {
echo $key->Id;
}
}
else {
echo $assignment->Id;
}
But if the code was a bit lengthy, I feel it is too repetitive and inefficient.
Is there a way to do this in one effective phrase no matter of the number of the contents inside the array? Let me know if anything is unclear. Thanks!
What you can do is change the non-array into an array with a single element, then you can process it consistently.
if (!is_array($assignment)) {
$assignment = array($assignment);
}
foreach ($assignment as $key) {
echo $key=>Id;
}

PHP adding to array in while loop

I'm having some trouble adding to an array during a while loop and was wondering if any of you could help me. Firstly, some background. I am looping through some sql results and trying to gather the results while grouping by various ids to make it easier to deal with later. It just seems to be one line of code that isn't working. There is some code below
while($row=mysql_fetch_assoc($res)){
if(!array_key_exists($row['foreign_key_value'],$contacts)){
$contacts[$row['foreign_key_value']]=array();
}
if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){
$contacts[$row['foreign_key_value']][$row['uid']]=array();
}
$contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value'];
}
It is the last line I am having trouble with, where I am adding rating_id and rating_value. The data I am looping through is 4 fields - foreign_key_value, uid, rating_id and rating_value. The structure I want to end up with looks like
array(1) {
[73]=>
array(2) {
[9]=>
array(1) {
[4]=>
string(1) "3"
}
[1762]=>
array(1) {
[1]=>
string(1) "5"
}
}
I just cannot get the rating_id and rating_value to create more than one key value pair in the last array, where I am expecting 5 pairs. The only thing I am getting is the last pair selected. I really have no idea why I'm not getting the data I need, can anyone help?
abc667 - you're spot on. Thank you very much. I've been staring at it so long I missed that and I'm starting to feel like an idiot now
You need to declare the $contacts array BEFORE the while() loop - so you can use it afterwards
$contacts = array();
while($row=mysql_fetch_assoc($res)){
if(!array_key_exists($row['foreign_key_value'],$contacts)){
$contacts[$row['foreign_key_value']]=array();
}
if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){
$contacts[$row['foreign_key_value']][$row['uid']]=array();
}
$contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value'];
}

&Array() - Final Row prefixed with ampersand after Updating Array

I am trying to update only some values of an Array directly. Which is working perfectly. I am using the following method:
foreach( $items as &$item ) {
if( $criteria == 'correct' ) {
// update array
$item['update_me'] = 'updated';
}
}
So I now have an updated array called $items.
However, the problem I have, is when this Array is output to screen (via another foreach loop), the last row of the Array is missing.
If I print the entire array via the var_dump( $items ); method, I noticed that each row is prefixed with Array(9). Yet the last row is prefixed with &Array(9) - notice the leading ampersand. I'm sure this is significant! But I'm unsure what it means. Why is it only applied to the final row in the Array? And how do I get rid of it?
From comment:
array(6) {
[0]=> array(9) {
["item_id"]=> string(4) "1"
["item_description"]=> string(9) "blah blah"
["quantity"]=> string(1) "4"
["unit_cost"]=> string(4) "5.00"
["subtotal"]=> string(4) "20.00"
}
[1]=> &array(9) {
["item_id"]=> string(4) "2"
["item_description"]=> string(9) "blah blah"
["quantity"]=> string(1) "1"
["unit_cost"]=> string(4) "5.99"
["subtotal"]=> string(4) "5.99"
}
}
You must unset $item after loop. Correct code:
foreach( $items as &$item ) {
if( $criteria == 'correct' ) {
// update array
$item['update_me'] = 'updated';
}
}
unset($item);
& sign in the var_dump result specify that this is reference. You can check it by using xdebug_zval_dump() function:
xdebug_zval_dump($item)
You'll see that is_ref=true. In PHP this means that there are another variables pointing to the same zval container (what is zval? see here http://php.net/manual/en/internals2.variables.intro.php).
If you're using & in loop you must always unset reference after the loop to avoid hard-to-detect errors.
I'm not sure if it is the case here, but by-reference foreach loops are known to cause these kind of problems if the reference is not unset after the loop (there's a warning about it in the manual). Try adding unset($item); right after the update foreach finishes and see if it solves the problem.
i think that's not the nicest way to do this. i'd suggest doing it this way:
foreach( array_keys($items) as $itemkey ) {
if( $criteria == 'correct' ) {
// update array
$items[$itemkey]['update_me'] = 'updated';
}
}

Categories