Add onto an array with the key and value - php

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?

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']);
}

you mean
$carIndex[$sellerName] = $vehicleName;

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"
)
)

Related

merge two columns into an array

I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm

add values into multidimensional array

I have a foreach loop that goes through a list of items. For each of these items, I have a while loop that grabs data out of a database.
$output = array();
//$reference is a multidimensional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
array_push($output[$color], $person);
}
}
So this loops through, the first time searching 'red', and finding 5 people in the fake table who like red. Next, 'blue', where it finds 1 person, and then 'green' where it finds 3.
If I look at the individual results, my first array has "red, blue, green" and my second array has these lists of names.... I just don't know how to add them into an array together.
I'm trying to build an array like this:
Array
(
[Red] => Array
(
[0] => John
[1] => Sally
[2] => Bob
...
)
[Blue] => Array
(
[0] => Luke
)
[Green] => Array
(
..etc...
)
I'm not using array_push correctly though - I'm getting an Warning: Illegal offset type error. What am I doing wrong?
It's been a while since I've worked with PHP, but I think you need to initialize each "color" array that you're going to push into. So...
$output = array();
//$reference is a multidimentional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
if (!array_key_exists($color, $output)) {
$output[$color] = array();
}
array_push($output[$color], $person);
}
}
Try changing:
array_push($output[$color], $person);
Into:
$output[$color][] = $person;
From the manual on array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

SQL - Separate results by associated vale?

Before anything, I'll show you my table:
(In the context of PHP)
I'd like to create a multidimensional array via a query - So that a group of tags with the same id will end up in the same place:
<?php
// Given the above example table, it would essentially produce this:
$my_1 = array
( array('ect'),
array('123', 'tag'),
array('lolly', 'hat')
);
Is that a possibility? I've achieved the same result by looping through queries, but it's terribly inefficient.
<?php
$array = array();
foreach($tags as $tag)
{
if(array_key_exist($tag->id,$array)){
//if key is assigned in array, we can push value to key
$array[$tag->id] = array_push($tag->value,$array[$tag->id]);
}else{
//if key is not assigned we will create key and push value
$array[$tag->id] = $tag->value;
}
}
//usage
print_r($array[7]); // list tags with id 7
?>
Use a 2-dimensional array:
$array = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$tag = $row['tag'];
if (isset($array[$id])) {
$array[$id][] = $tag;
} else {
$array[$id] = array($tag);
}
}
The resulting $array will be
array(1 => array('ect'),
7 => array('123', 'tag'),
9 => array('lolly', 'hat'))

PHP MYSQL multidimensional array

I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!

Why my php array is over written when they have same Keys

I have a custom PHP function which executes a stored procedure and returns an array:
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim = array();
foreach ($result['recordset'] as $rows) {
if (!empty($rows)) {
echo $arr_sim[$rows['field1']] = $rows['field2'];
}
}
return $arr_sim;
}
In the above function $arr_sim is returning the number of items correctly when the rows["field1"] values are different. If the rows["field1"] values are the same then it is overwriting the first value and returning only the last one. How can I overcome this?
array ( [chicago] => 'sears', [rochester] => 'liberty' )
If the $arr_sim contains these items then it is returned correctly. Because the keys are different.
array ( [chicago] => 'MCD', [chicago] => 'TACOBELL' )
If the $arr_sim contains these items then it is not returned correctly. Because the keys are the same, "chicago".
Array keys must be unique. Instead, do something like this:
// You want the array to look like this
// array('chicago' => array('MCD', 'TACOBELL'));
function test(){
$in = array("abc","bcd","efg");
$result = mydba->executestoredprocedure('proc1',$in);
$arr_sim=array();
foreach ($result['recordset'] as $rows) {
if(!empty($rows)){
if(array_key_exists($rows['field1'], $arr_sim) {
$arr_sim[$rows['field1']][] = $rows['field2'];
} else {
$arr_sim[$rows['field1']] = array($rows['field2']);
}
}
}
return $arr_sim;
}
Replace $arr_sim[$rows['field1']] = $rows['field2'] with $arr_sim[$rows['field1']][] = $rows['field2']. This will create an array of arrays.
echo $arr_sim['chicago'][0]; // MCD
echo $arr_sim['chicago'][1]; // TACOBELL
Technically, you should write something like this to avoid notices:
if (!isset($arr_sim[$rows['field1']])) $arr_sim[$rows['field1']] = array();
$arr_sim[$rows['field1']][] = $rows['field2'];
But you must really ask yourself, is the field1 (city names) worthy of being the primary key for the array? If not, you should choose some other identifier.

Categories