How to add new key-value to existing array in PHP - php

I have a form in PHP that takes in two values: server_id and user_id (which can be more than one separated by ','). I retrieve some data from a table and stored them as array. Using the same server_id and user_id, I would like to retrieve additional from another table but store them into the same array.
This is what I have so far.
//Data from PHP form stored in array
$inputData = Array ( [server_id] => 10
[user_id] => Array ( [0] => 111[1] => 222) )
//Existing array storing data retrieved from persons table
$userData =
Array
(
[0] => Array
(
[user_id] => 111
[server_id] => 10
[user_name] => Harry Pottter
[user_age] => 18 )
[1] => Array
(
[user_id] => 222
[server_id] => 10
[user_name] => Hermione
[user_age] => 18 )
)
//retrieving additional data from user_contact table
$sql = "SELECT user_phone, user_address FROM user_contact
WHERE user_id = ? AND server_id = ?";
foreach($user_id as $user)
{
$statement= $DB->link->prepare($sql);
$statement->bind_param("si", $server_id, $user);
$statement->execute();
if($resultSet = $statement->get_result())
{
while($row = $resultSet->fetch_assoc())
{
userData[$key]['user_phone'] = $row['user_phone'];
userData[$key]['user_address'] = $row['user_address'];
}
}
}

try using array_push()
like
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Related

php select a random array value within while loop and assign it to a variable

How can I get and assign a random array value from array inside a while loop to a variable?
Code
$stmt = $pdo->prepare("SELECT mem_id FROM members WHERE mem_id NOT IN (SELECT ref_referral FROM referrals)");
$stmt-> execute();
$rec = array();
while($f = $stmt->fetch()){
$rec[] = $f;
}
print_r($rec);
The above code returns this array
Array
(
[0] => Array
(
[mem_id] => 2
[0] => 2
)
[1] => Array
(
[mem_id] => 3
[0] => 3
)
[2] => Array
(
[mem_id] => 4
[0] => 4
)
)
Now if I want to take one value from either of 2,3,4 randomly and assign it to a variable say $randomValue = $randomValueFromArray, how can I do that?

Two Array's Trying to Combine where A Value is equal to a key?

I Have Two Array's One That is a 'App' Array and one is a 'Table' Array. Each Row in 'Table' has an 'AppID' As Shown Below. How can I combine the array to where the App_ID in the Tables Array is under the Same App_ID on the App Array? What I Currently Have is First and Want I Want is after that. I am using PHP. Thank Your for all of the Help!
App Array:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Project Manager
[App_Created] => 2014-12-17 16:31:57
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
Tables Array:
Array
(
[1] => Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
)
[2] => Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
I Want to Go to:
Array
(
[1] => Array
(
[App_ID] => 1
[App_Name] => Kennedy_Fabricating_Project_Manager
[App_Created] => 2014-12-17 16:31:57
[Tables] = > Array
(
[Table_ID] => 1
[App_ID] => 1
[Table_Name] => Customers
),
Array
(
[Table_ID] => 2
[App_ID] => 1
[Table_Name] => Jobs
)
)
[2] => Array
(
[App_ID] => 2
[App_Name] => Estimating
[App_Created] => 2014-12-17 23:49:40
)
)
My Current PHP Code:
//Get App List
$apps_sql = $conn->query("SELECT * FROM `Apps`") or die("Conn Query Apps Failed");
$apps = array();
while($apps = $apps_sql->fetch_array(MYSQLI_ASSOC)) {
$app_id = $apps['App_ID'];
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE `App_ID` = $app_id") or die("Conn Query Tables in Apps Failed");
// My Guess is Something Here?
$apps_a[$app_id] = $apps;
}
// Table List
$table_sql = $conn->query("SELECT * FROM `Tables`") or die("Conn Query Tables Failed");
$tables = array();
while($tables = $table_sql->fetch_array(MYSQLI_ASSOC)) {
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
}
It looks cleaner, and faster as you make only 2 queries instead of zillions
$apps_sql = $conn->query("SELECT * FROM `Apps`");
$apps_ids = array();
while ($app = $apps_sql->fetch_array(MYSQLI_ASSOC))
{
$apps_ids[] = $app['App_ID'];
$apps[$app['App_ID']] = $app;
}
$apps_ids = implode(',', $apps_ids);
$table_sql = $conn->query("SELECT * FROM `Tables` WHERE IN ({$apps_ids})");
while($table = $table_sql->fetch_array(MYSQLI_ASSOC))
{
$apps[$table['App_ID']]['tables'][] = $table;
}
just change:
$table_id = $tables['Table_ID'];
$tables_a[$table_id] = $tables;
into:
$apps_a[$tables['App_ID']]['Tables'][$tables['Table_ID']] = $tables;

Mysqli fetching data from two columns

I have 3 tables users(id,name,etc..), trips(id,user_id,from,to,destionation) , vactions(id,user_id,from,to,destionation).
I use mysqli and i can not figure out how to do this
I need to fetch this table like this
Array
(
[0] => Array
(
[id] => 1
[current_status] => 0
[username] => user1
[fullname] => Eric Norman
[trips] = > Array
(
[0] => Array
(
[date_from] = 02/06/14
[date_to] = 05/06/14
[destination] = "Grece"
)
[vacations] = >
)
[1] => Array
(
[id] => 2
[current_status] => 0
[username] => user2
[fullname] => Joe Grey
[trips] = > Array
(
[0] => Array
(
[date_from] = 02/06/14
[date_to] = 05/06/14
[destination] = "Grece"
)
[vacations] = >
)
)
I've tried with left join but i doesn't work and my code now is only for users :
conn = new mysqli($host,$user,$password,$db);
$result = mysqli_query($conn, "SELECT id, current_status, username, CONCAT(first_name,' ',last_name) as fullname FROM user");
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
I think the best way is to get all users, then use a foreach to get all trips and vacations.
Because I'm not sure you can obtain this kind of array result using a simple SQL query, I think ou need an ORM.
$users = getAllUsers();
foreach($users as $user){
$user['trips'] = getTripsByUserId($user['id']);
$user['vacations'] = getVacationsByUserId($user['id']);
}
Of course you need to code the 3 methods "getAllUsers" ; "getTripsByUserId" and "getVacationsByUserId" which are only simple SELECT query to database with a where clause.

PHP SQL: GROUP BY as array index

I have this query for mysql:
SELECT HOUR(time),COUNT(*) FROM pageview WHERE time >= DATE_SUB(NOW(),INTERVAL 12 HOUR) GROUP BY HOUR(time)
For example, this is the output:
Array
(
[0] => Array
(
[HOUR(time)] => 1
[COUNT(*)] => 1
)
[1] => Array
(
[HOUR(time)] => 10
[COUNT(*)] => 4
)
[2] => Array
(
[HOUR(time)] => 11
[COUNT(*)] => 5
)
)
However I want the output like this
Array
(
[1] => 1
[10] => 4
[11] => 5
)
The array index should be the value of [HOUR(time)].
I would prefer directly by changing the query.
To fetch the data I use this:
$stmt = $db->prepare($query);
$result = $stmt->execute();
$views = $stmt->fetchAll();
indexes in mysql results create automatically , to achieve your goal loop through your first array and create new one as you want
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = array( 'COUNT(*)' => $row['COUNT(*)']);
}
print_r($result); // check output
or simpler form
$result = array();
foreach($views as $row) {
$result[$row['HOUR(time)']] = $row['COUNT(*)'];
}
print_r($result); // check output
Try with this
$res = array();
foreach($views as $data)
{
$res[$data['HOUR(time)']] = array( 'COUNT(*)' => $data['COUNT(*)']);
}
print_r($res);

PHP and SQLite - Multiply Certain Column Values Together

I'm retrieving some data from a database where the values might be something like the following:
Column1 | Column2
-----------------
Bob | 24
Joe | 17
Jimmy | 38
Joe | 10
Bob | 5
Sam | 8
With this data, I want to somehow select the Bob rows and multiply them together. I want to do this for all rows that match in Column1. I'm not concerned about doing it in SQLite, but what is the best way to go about this in PHP? I've currently added the results to an array in PHP by doing the following:
$myArray[$resultRow['Column1']] = $resultRow['Column2'];
I was wondering how to go about navigating through this and finding matching keys, multipying their values together, and outputting something like
Column1 = Column2-a * Column2-b
consider this code:
$results = array();
foreach(array('Bob' => 24, 'Joe' => 17, 'Jimmy' => 38, 'Joe' => 10, 'Bob' => 5, 'Sam' => 8) as $key => $val){
$results[$key][] = $val;
}
echo '<pre>';
print_r($results);
echo '</pre>';
out put:
Array
(
[Bob] => Array
(
[0] => 5
)
[Joe] => Array
(
[0] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
PHP ignores duplicate key, you have to create $results array when you retreiving the data from database, lets assume that you do like this:
while () {
$col1 = $row["col1"];
$col2 = $row["col2"];
$results[$col1][] = $row["col2"];
}
now the results array must be like this:
Array
(
[Bob] => Array
(
[0] => 24
[1] => 5
)
[Joe] => Array
(
[0] => 17
[1] => 10
)
[Jimmy] => Array
(
[0] => 38
)
[Sam] => Array
(
[0] => 8
)
)
now, its easy to search for colmun1 names like this:
$values_for_colmn1 = $results[$column1]; //which is an array
// use array_product() function for array product
$product_for_column1 = array_product($values_for_colmn1);
First, to read only Bob's values:
$stmt = $db->prepare('SELECT Column2 FROM MyTable WHERE Column1 = ?')
$stmt->bindValue(1, 'Bob', SQLITE3_TEXT);
$result = $stmt->execute();
Then, multiply all of them:
$value = 1.0;
while ($res = $result->fetchArray()) {
$value = $value * $res['Column2'];
}

Categories