PHP Key List => Values

this is my first topic on this site; I'm a newbie just starting out with PHP.

I saw that my question was asked and answered several times; I think I read almost all of them, but I did not find a definitive answer.

I need to send from PHP (V. 5.5) the result of a MySQL query to a jQuery function. It is important for me that the sent text string should be in the form: FieldName = FieldValue

I tried most of the suggestions found on this site, but actually I get a double entry for each field called "Index: keyname". In other words, each field is sent twice, and the value associated with fied is missing.

The final test was performed using this code:

foreach(array_keys($row) as $key => $valore) { echo ($key." --> value= ".$valore."<br/>"); } 

I really get:

 0 --> value= 0 1 --> value= IDcomponent 2 --> value= 1 3 --> value= IDtype 4 --> value= 2 5 --> value= Manufacturer .... 

while I will need:

 IDcomponent = 100 IDtype= 5 Manufacturer = Texas ... 

With this alternate code:

 $fields=mysql_num_fields($result); for ($ix=0; $ix<$fields; $ix++) { $ky = $row[$ix]; echo ($ky." = ".key($ky)."<br>"); } 

I get (in the example):

 100 = 5 = Texas = 

The key name is empty.

I hope this is clear enough; sorry for any mistake.

Any help would be really appreciated, thanks

+4
source share
2 answers

I think you are looking for:

 foreach($row as $key => $valore) { echo ($key." --> value= ".$valore."<br/>"); } 

With array_keys() you only array_keys() over an array of arrays.

+3
source

Thanks @Tobias; I tried your code before, but in response I got twice as many as one line.

Actually, I solved my stupid problem with a workaround. The solution uses the same code that you suggested, followed by IF, to check the odd / even lines, and then send only the odd ones. Cruel, but he does the job, waiting to understand what I did wrong.

 $cnt=0; foreach($row as $key=>$value) { if (($cnt & 1)) echo $key."|".$value."ยง"; $cnt++; } 

Thanks to @treegarden, too, who gave me an interesting hint of an investigation.

+1
source

All Articles