简体   繁体   中英

php, mysql, arrays - how to get the row name

I have the following code

while($row = $usafisRSP->fetch_assoc()) {
    $id = $row['id'];
    $Applicantid = $row['Applicantid'];
    $unique_num = $row['unique_num'];

    // .................

    $hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
    $hidden_values = array();

   foreach ($hidden_fields as $key => $value) {
       $hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
       echo $hidden_values[$value];
   }
}

and the result is something like this

0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA

I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like

id = 116153840
application name = 136676636
etc ..
how can I do that ?

I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row .

I would create an array that specifies the hidden fields:

$HIDDEN = array(
     'id' => 'Id', 
     'Applicantid' => 'application name', 
     'unique_num' => 'whatever'
);

And then in your while loop:

while(($row = $usafisRSP->fetch_assoc())){

    $hidden_fields = array();

    foreach$($HIDDEN as $field=>$name) {
        $hidden_fields[$name] = $row[$field];
    }

    //...

    foreach($hidden_fields as $name => $value) {
        $hidden_fields[$name] = $name . ' = ' . base64_decode($value);
        echo $hidden_values[$name];
        // or just echo $name, ' = ',$hidden_fields[$value];
    }
}

Replace the $hidden_fields = array(... line with the following:

$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));

If you want to suppress all fields with value 0, either use

$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});

(this will completely omit the 0-entries) or

$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});

(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.

foreach ($row as $key => $value) {
   $hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
   echo $hidden_values[$value];
}

This could give you something relevant. Through accessing the string keys from the row array which contains the string keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM