开发者

PHP Array Differences - Generated by Loop vs String Comma-Separated

开发者 https://www.devze.com 2023-03-13 05:51 出处:网络
I am using jQuery Autocomplete (http://code.google.com/p/jquery-autocomplete/) and having some problems when I use an array generated by a MySQL call. Is there a fundamental difference between an arra

I am using jQuery Autocomplete (http://code.google.com/p/jquery-autocomplete/) and having some problems when I use an array generated by a MySQL call. Is there a fundamental difference between an array created in PHP using strings versus creating one in a loop?

For example, if I create array using string, like in the example, everything works fine. ie:

$items = array(
    "Great Bittern" => "Botaurus stellaris",
    "Little Grebe" => "Tachybaptus ruficollis")

When I create the array as below, it seems the array is not recognized, or maybe the data within the array is not searchable:

$items = array();
$query = mysql_query("MY QUERY");
while ($row = mysql_fetch_array($query))
{
array_push($data, $row['开发者_开发技巧name']);
}

Is it because the MySQL call is made after the php file including it has been loaded? I've experimented with many, many variations of creating the array in the loop, and none have worked.

Thanks in advance for any advice or tips. Pulling my hair out over this one!


Your two examples do fundamentally different things.

In the first example, you have what most languages would call a "hash" or a "map"; a series of key/value pairs mapping one string to another. "Great Bittern" would be the key, and "Botaurus stellaris" would be the corrosponding value.

In the second you have a more traditional numerically indexed array with sequential keys. There is nothing preventing you from creating a map the way you did in the first example, you simply need to explicitly specify the string key instead of using array_push. If your query is returning two associated values, you would do something like

$data[$row['key']] = $row['value'];

Which approach you use depends on what kind of data your jQuery plugin expects to receive. Does it want a key/value map, or an array of values?

0

精彩评论

暂无评论...
验证码 换一张
取 消