简体   繁体   English

PHP数组差异-由循环与字符串逗号分隔生成

[英]PHP Array Differences - Generated by Loop vs String Comma-Separated

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. 我正在使用jQuery Autocomplete(http://code.google.com/p/jquery-autocomplete/),并且在使用由MySQL调用生成的数组时遇到了一些问题。 Is there a fundamental difference between an array created in PHP using strings versus creating one in a loop? 使用字符串在PHP中创建的数组与在循环中创建一个数组之间有根本区别吗?

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? 是因为MySQL调用是在包含它的php文件加载后进行的? 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. “ Great Bittern”将是关键,而“ Botaurus stellaris”将是相应的价值。

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 . 没有什么会像第一个示例中那样阻止您创建映射,您只需要显式指定字符串键,而不是使用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. 您使用哪种方法取决于jQuery插件期望接收哪种数据。 Does it want a key/value map, or an array of values? 是否需要键/值映射或值数组?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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