如何删除额外的数组值

时间:2012-08-05 18:36:38

标签: php mysql

我有一个PHP脚本执行此操作:

  • 将UPC置于表格
  • 提交表格
  • 检查我的数据库中是否已存在UPC
    • 如果是,请从MySQL数据库中获取
    • 如果没有,请从外部服务器获取,将其添加到MySQL数据库以备将来使用
  • 显示结果

它工作正常,但我希望变量看起来与MySQL缓存或外部服务器完全相同。

当我从服务器打印时,它看起来像这样:

输出:

[upc] => 066721020215
[pendingUpdates] => 0
[status] => success
[ean] => 0066721020215
[issuerCountryCode] => us
[found] => 1
[description] => Christie - Original Ritz Crackers
[message] => Database entry found
[size] => 225 g
[issuerCountry] => United States
[noCacheAfterUTC] => 2012-08-06T12:23:58
[lastModifiedUTC] => 2009-04-06T01:51:08

但是,当我从MySQL打印数组时,它看起来像这样:

$result = mysql_query("SELECT * FROM UPC WHERE `upc` = '$codes[0]'");
$data = mysql_fetch_array($result);
echo "<pre>" . print_r($data, true) . "</pre>";

输出:

[0] => 066721020215
[upc] => 066721020215
[1] => 0
[pendingUpdates] => 0
[2] => success
[status] => success
[3] => 0066721020215
[ean] => 0066721020215
[4] => us
[issuerCountryCode] => us
[5] => 1
[found] => 1
[6] => Christie - Original Ritz Crackers
[description] => Christie - Original Ritz Crackers
[7] => Database entry found
[message] => Database entry found
[8] => 225 g
[size] => 225 g
[9] => United States
[issuerCountry] => United States
[10] => 2012-08-06
[noCacheAfterUTC] => 2012-08-06
[11] => 2009-04-06
[lastModifiedUTC] => 2009-04-06

我意识到它或多或少是一个整容差异(并且数组的大小是它需要的两倍),但是如何在不循环数组的情况下轻松删除0,1,2,3等标识符创建并手动创建一个新的?是否有一个可以删除编号标识符的函数?

2 个答案:

答案 0 :(得分:2)

您需要使用mysql_fetch_array($result, MYSQL_ASSOC)mysql_fetch_assoc($result)

有关详细信息,请参阅http://php.net/manual/en/function.mysql-fetch-array.phphttp://www.php.net/manual/en/function.mysql-fetch-assoc.php

请注意,两者都不鼓励,因为它们已被新的(ish)mysqli函数取代:http://uk.php.net/manual/en/book.mysqli.php

答案 1 :(得分:2)

更改行:

$data = mysql_fetch_array($result);

为:

$data = mysql_fetch_assoc($result);

mysql_fetch_assoc以关联数组的形式返回数据库中的数据 - mysql_fetch_array返回一个包含数字和关联索引的混合数组。

请参阅http://php.net/manual/en/function.mysql-fetch-assoc.php