Scott Scott - 9 months ago 27
PHP Question

PHP store a value from a While loop in an associative manner for external use?

This is only a personal project. So yes, it's using mysql, but it's not commercial and only running on localhost. So, not really imperative I update it to mysqli or anything. I'm also not a developer and dabble with php for personal databases. So, forgive me if my code is horrendous, I'm eager to improve if you'd care to share.

I've constructed a while loop to fill arrays. This allows me to check against those arrays in another while loop. The goal being to improve efficiency and not just run loops, within loops, within loops.

For the most part this works fine. I'm trying to extend the capabilities though and hitting a hurdle.

// query to pull data. / GROUP BY id
// pulls multiple results, but I merely want the results for each distinct ID.

$r = 0;
$u = 0;
$n = 0;
$checkarr=array();
$mustarr=array();
$badarr=array();
$idarr=array();

while ($row = mysql_fetch_array($qry)) {
$check = $row['tbl.check'];
$must = $row['tbl.must'];
$thisid = $row['tbl.id'];

if ($check == 1) {
$checkarr[] = $thisid;
$n++; }

if ($must == 'R') {
$badarr[] = $thisid;
$r++; }

if ($must == 'U') {
$mustarr[] = $thisid;
$u++; }
}


This works to fill the arrays properly with the ID for comparison later. I can just run
in_array([id], $checkarr)
to see if they match.

What I'm trying to do and failing miserably at... is to fill some sort of associative array so that each
$thisid
is associated with the final values of
$n
,
$r
, and
$u
. That way, later I can somehow call
$thisid['r']
and get the total value of
$r
associated with that ID.

Something like....

(Pseudo code)

if((in_array($loopid, $mustarr)) {
//display value of $r associated with the $loopid
}


I've tried foreach() loops and just am not figuring it out properly.

How can I associate the total values of $n, $r, and $u with $thisid? Primarily so that I can pull each value outside of this specific loop?

Any tips would be appreciated.

Answer Source

You could make $thisid and your other arrays associative arrays.

$r = 0;
$u = 0;
$n = 0;
$checkarr = array();
$mustarr = array();
$badarr = array();
$idarr = array();

while ($row = mysql_fetch_array($qry)) {
   $check = $row['tbl.check'];
   $must = $row['tbl.must'];
   $thisid = array('id' => $row['tbl.id'], 'n' => $n, 'r' => $r, 'u' => $u);

   if ($check == 1) { 
       $checkarr[$row['tbl.id']] = $thisid; // To make it easier to find $thisid later
       $n++; }

   if ($must == 'R') { 
       $badarr[$row['tbl.id']] = $thisid; 
       $r++;  }

   if ($must == 'U') { 
       $mustarr[$row['tbl.id']] = $thisid;
       $u++; }
}

If you want to check, if an id is in one of the arrays you could use array_key_exists:

if(array_key_exists($loopid, $mustarr)){
     echo $mustarr[$loopid]['r']; // Displaying $r for $loopid
}