Reputation: 431
I've looked for days and to no avail. I can't find a function which could add to an array with the key and value. Here's why I need it: I need an array to store both the name of the owner and the type of the car. I'd like for the key to be the name of the owner and the type of the car to be the value and not have to use two arrays to contain something which one array can.
Here's my current code:
Function used to get $vehicleName
function carName($nakedCarString)
{
$cars=(separateString($array, $vehicleString));
return $cars[0];
}
The above code uses a vehicle string, gets the name of the car with an array and returns the name of the car in a string. Not an array.
Code(which requires code to add to array with key and value) which will be adding info to array
while($row = mysql_fetch_array($result))
{
$vehicleString = $row['Vehicle'];
$vehicleName = carName($vehicleString);
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$sellername = $name->getFriendlyName();
}
The above code gets each row in a mysql table and foreach row it'd get the vehicle string, the name of the car from vehicle string using function above, the seller and the sellers name(in string, not array)
I'd need it so that it could add to an array($carIndex) with the key($sellername) and value($vehicleName). Any help?
Upvotes: 1
Views: 191
Reputation: 47874
In modern PHP, mysqli result objects are directly accessible in a foreach loop as if they were a 2d array. Access the column values from the database and construct your new array with two-element rows.
The script below uses array destructuring syntax to only access column values which are relevant. No other single-use variables are declared.
$vehicles = [];
foreach ($result as ['Vehicle' => $v, 'Auctioneer' => $a]) {
$vehicles[] = [
'vehicleName' => carName($v),
'sellerName' => (new SteamAPI(
steamID2CommunityID($a)
))->getFriendlyName();
];
}
Upvotes: 0
Reputation: 10067
I would not recommend you to use the name as a key in the array, as it might contain invalid characters, why don't you use a multi-dimensional array instead:
$cars = array();
while($row = mysql_fetch_array($result))
{
$array = array();
$vehicleString = $row['Vehicle'];
$array['vehicleName'] = carName($vehicleString);
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$array['sellerName'] = $name->getFriendlyName();
$cars[] = $array;
}
Exmaple output:
Array (
[0] => Array
(
['vehicleName'] => "Ford"
['sellerName'] => "John Sr."
)
[1] => Array
(
['vehicleName'] => "Audi"
['sellerName'] => "Jane-Doe"
)
)
Upvotes: 0
Reputation: 33891
You are overcomplicating this:
$cars= array();
while($row = mysql_fetch_array($result))
{
$seller = steamID2CommunityID($row['Auctioneer']);
$name = new SteamAPI($seller);
$sellername = $name->getFriendlyName();
$cars[$sellername] = carName($row['Vehicle']);
}
Upvotes: 2