user1393215
user1393215

Reputation:

How to remove extra array values

I have a php script does this:

It works fine, but I'd like the variable to look exactly the same wether it comes from the MySQL cache, or the external server.

When I print it from the server, it looks like this:

Output:

[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

However, When I print the array from MySQL, it looks like this:

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

Output:

[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

I realize it's more or less a cosmetic difference (and an array twice as big as it needs to be), but how would I go about easily removing the 0,1,2,3,etc identifiers without looping through the array creating and manually creating a new one? Is there a function that would remove the numbered identifiers?

Upvotes: 1

Views: 199

Answers (2)

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

Change the line:

$data = mysql_fetch_array($result);

to:

$data = mysql_fetch_assoc($result);

mysql_fetch_assoc returns the data from the db as an associative array - mysql_fetch_array returns a mixed array, with both numeric and associative indexes.

See http://php.net/manual/en/function.mysql-fetch-assoc.php

Upvotes: 1

Grim...
Grim...

Reputation: 16953

You need to use mysql_fetch_array($result, MYSQL_ASSOC) or mysql_fetch_assoc($result).

See http://php.net/manual/en/function.mysql-fetch-array.php and http://www.php.net/manual/en/function.mysql-fetch-assoc.php for more details.

Note that both are discouraged, as they have been replaced by the new(ish) mysqli functions: http://uk.php.net/manual/en/book.mysqli.php

Upvotes: 1

Related Questions