PHP adding to array in while loop - php

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'];
}

Related

PHP, jQuery passing JSON array turns to object, how to keep it an array

I have a PHP array, that I want to pass over to jQuery and update the rows on the page.
This PHP array is the 'name' of the checkboxes selected on the page. (So this array can be of any length, depending on what the user selects)
PHP Array:
var_dump($sr->conflict_return);
OUTPUT CHECK: array(5) { [0]=> string(33) "hours_9_7_reg_session_102_905_925" [1]=> string(33) "hours_9_7_reg_session_101_905_925" [2]=> string(33) "hours_9_7_reg_session_103_905_925" [4]=> string(33) "hours_9_7_reg_session_104_845_915" [13]=> string(33) "hours_9_7_reg_session_103_845_905" }
This this case... there are '5' elements in my [php] array.
Here is where my problem comes into play...
Sometimes it 'works'... sometimes it doesnt..
The 'key' seems to be what is IN the array:
OUTPUT CHECK: array(3) { [0]=> string(33) "hours_9_7_reg_session_102_845_905" [1]=> string(33) "hours_9_7_reg_session_101_845_905" [2]=> string(33) "hours_9_7_reg_session_104_845_915" }
this seems to work.. 3 items in array.. all 3 rows on stage get highlighted.
this:
OUTPUT CHECK: array(4) { [0]=> string(33) "hours_9_7_reg_session_102_845_905" [1]=> string(33) "hours_9_7_reg_session_101_845_905" [2]=> string(33) "hours_9_7_reg_session_103_845_905" [4]=> string(33) "hours_9_7_reg_session_104_845_915" }
doesnt work... and none of the rows are highlighted
(seems like if there is 4 items in the array it breaks??)
my jQuery to parse the data:
var conflictItems = <?=json_encode($sr->conflict_return); ?>;
//has a conflict list
if(conflictItems.length > 0){
alert("Has conflicts");
//loop through and highlight elements on stage
for(i=0; i<conflictItems.length; i++){
console.log(conflictItems[i]);
$("#sr_table_"+conflictItems[i]+"_row").addClass("conflict_border");
}
}
When I trace (console.log()) the data.... I get odd results.
console.log('CONFLICT ITEMS: ' + conflictItems);
console.log('CONFLICT COUNT: ' + conflictItems.length);
3 x items in array... the above shows:
CONFLICT ITEMS: hours_9_7_reg_session_103_845_905,hours_9_7_reg_session_102_845_905,hours_9_7_reg_session_104_845_915
CONFLICT COUNT: 3
which to me is correct. I have 3 items in my array passed over from PHP..jQuery runs through list and adds a class to each 'row'.
however, when I add a 4th item... the traced output is:
CONFLICT ITEMS: [object Object]
CONFLICT COUNT: undefined
So how? is my array turning into an object?.. and more so WHY??
and how can I fix this? I dont understand why having 3 items in the array works.. but not 4?
Javascript doesn't have a concept of non-sequential array keys (your example has keys 0,1,2 and 4), thus when running json_encode on the array, it converts it to JSON notation for a JS object.
As #Kenney says in the comments, a possible solution is to keep using arrays, but make use of array_values() function which takes your array, and basically regenerates the array dropping the existing keys and using sequential ones.
You're missing index 3 from your array, therefore js turns it into an object.

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;
}

Sorting a sub-array in a multidimensional array in PHP [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I know similar questions to this have been asked, but even looking at all of them, I can't seem to get this to work. I think it's just a tad bit more complex than the other examples I'm finding. I know someone is going to say it's a repeat question - but I've tried really hard to get it from the examples I've seen so far - so sorry in advance!
So given this multidimensional array $results_display in PHP (var_dump below), there are 5 members of the sub-array "#results", and I want to sort (descending) those 5 by the value in the "#changed" string.
Can someone please help a girl out who's been banging her head against her desk for a couple days?
Thank you so much!!!
What I tried is below the var_dump. I commented out the part with the title to try and get just the first part working.
$results_display =
array(8) {
["#theme"]=> string(18) "hs_filters_results"
["#title"]=> string(18) "On-Demand Webinars"
["#body"]=> NULL
["#results"]=> array(5) {
[0]=> array(3) {
["#changed"]=> string(10) "1403279484"
["#theme"]=> string(17) "hs_filters_result"
["#result"]=> array(25) {
["#nid"]=> string(4) "2057"
["#node_type"]=> array(2) {
["machine_name"]=> string(7) "webinar"
["name"]=> string(7) "Webinar" }
["#title"]=> string(61) "7 Critical Reasons to Automate Handling of IBM i Spool Files "
["#brand_nid"]=> string(2) "29"
["#brand_machine_name"]=> string(5) "brand"
... }
}
...
}
// Obtain a list of columns for the results array
foreach ($results_display as $key => $row) {
$changed[$key] = $row['changed'];
//$title[$key] = $row['title'];
}
// Sort the data with date changed descending, title ascending
// Add $results_display as the last parameter, to sort by the common key
//array_multisort($changed, SORT_DESC, $title, SORT_ASC, $results_display);
array_multisort($changed, SORT_DESC, $results_display);
usort($results_display['results'], function ($a, $b) {
return $a['changed'] - $b['changed'];
});
This should get you started. For more possible sorting options, see https://stackoverflow.com/a/17364128/476.

Assign value to array in for loop

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.

How do I get my values out of their SimpleXMLObjects?

After an xPath, I'm left with this var_dump:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (1) {
[0]=>
string(11) "22-99586795"
}
}
echoing the damn thing only gives me "Array()"
How do I get the bloody string out?
Thanks
It's an array with one item, so you need to do:
$myelement[0];
or
$myelement[0][0];
(I can't tell from your question which element you're referring to)
Try casting it to string
print (string)$yourarray[0];

Categories