how to replace values in array with values from another array? - php

I'm fetching an array:
$sql = SELECT id, name, state FROM table ORDER BY name
$result = mysqli_query($conn, $sql);
$rows = array();
$dict = ["A","B","C"];
while ($row = mysqli_fetch_array($result)) {
//replace state value here before next line
$rows[] = $row;
}
Values in the state field can be 0,1,2. I want to replace the value in key=state of $row with the value from $dict so 0=>A, 1=>B, 2=>C. Value in state field equals position of $dict array.
ex. if $row=["id"=>"1","name"=>"john", "state"=>"1"]
new $row=["id"=>"1","name"=>"john", "state"=>"B"]

You can use like that:
$dict = array("A","B","C");
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$rows[$i]['id'] = $row['id'];
$rows[$i]['name'] = $row['name'];
$rows[$i]['state'] = $dict[$value['state']];
$i++;
}
If your $dict index is fixed into three index than it will work perfectly.
Explanation:
$dict[$value['state']] this will get the value as per index value.
Like if $value['state'] == 1 than it will get the "B" from $dict array.
For the safe hand you can also use like that:
$rows[$i]['state'] = (isset($dict[$value['state']]) ? $dict[$value['state']] : ''); // if not set than empty anything else that you want.

Related

How to filter an implode result by a condition?

I am trying to implode data MySQL database.
I have an implode result like this :
1,2,3,4,5
And what I want is like this (I want filter number 3 from the result) :
1,2,4,5
What I have done :
$result = [];
$query = mysqli_query($koneksi, "SELECT * FROM user") or die (mysqli_error());
while($row = mysqli_fetch_assoc($query)){
$result[] = $row['id'];
$implode = implode(",", $result);
echo $implode;
Is there any way to filter that result?
You can use the 'if' construct
Find this code:
$result[] = $row['id'];
if you need to compare a variable with a value, instead of doing:
Change this line with:
if($row['id'] != '3'){
$result[] = $row['id'];
}

array_sum returning the sum of values as string

This seems like it should be really straightforward, but I keep getting unexpected output. I'm trying to access specified rows in a SQL database which each contain a numerical value and then calculate the sum of those values. PHP is concatenating the values as if they were strings even after I've set the datatype of the values to float. My code:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
$population_value = is_array($population_value) ? $population_value : array($population_value);
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I have also tried:
$total = array("");
foreach($population_value as $value){
floatval($value);
array_push($total, $value);
echo $value;
}
echo array_sum($total);
My output is always something like: 100002000030000
with 10,000 20,000 and 30,000 being the values of each population.
I've successfully calculated sums using foreach with values that weren't retrieved from MySQL.
What is going on here?
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)) {
$population_value = $row['population_value'];
//This is actually rewriting the array or NOT adding the value to it.
$population_value = is_array($population_value) ? $population_value : array($population_value);
//ok, so you're going to repeatedly output this?
foreach($population_value as $value){
echo $value;
}
echo array_sum($population_value);
}
I think what you want is this:
$query = "SELECT * FROM populations WHERE username ='{$_SESSION[name]}' AND region_name = 'region'"
$query .= "AND city_name = 'city'";
$result = mysqli_query($connection, $query);
$population_value=array(); //Initialize the array so we can just add to it.
while($row = mysqli_fetch_assoc($result)) {
$population_value[]= intval($row['population_value']); //Just making sure we get a number.
echo end($population_value); //We could output the row again, or just grab the last element of the array we added.
}
//Now that the array is fully populated and we've made sure it's only numbers, we output the grand total.
echo array_sum($population_value);
First, don't initialize the array with an empty string. Do this instead:
$total = array();
or with the new style:
$total = [ ];
Second, rewrite the floatval thing like this:
array_push($total, floatval($value));
That should fix it...

Convert Selected row to JSON - PHP

I want to convert selected result into JSON.
Here is my code:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id,user.name,user.email,ac_detail.ac_id,ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
$a=array("users"=>$usersArray);
//$row["user"]=$usersArray
array_push($row,$a);
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
?>
By executing this code it generate JSON like :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","0":{"users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}}]}
But i don't want "0"{"user::...}
How it should be (Expected Results) :
{"data":[{"ac_id":"1","user_id":"2","title":"Travel","ac_for":"Traveling","required_amount":"50","current_amount":"0","initial_date":"2014-11-11","final_date":"2014-11-14","is_shared":"1","status":"1","users":[{"user_id":"2","name":"Muhammad Imran","email":"macrotechnolgies#gmail.com","ac_id":"1","amount":"0"},{"user_id":"3","name":"Muhammad Imran","email":"macrotecholgies#gmail.com","ac_id":"1","amount":"0"}]}]}
Thanks in advance
You're doing:
while($row = mysqli_fetch_assoc($sth)){
[...snip...]
array_push($row,$a);
The while line creates an array $row, which you then use parts of to create $a. You then push that $a BACK onto the original $row array. But $row is an associative array already, so the pushed $a gets key 0.
Since you're now mixing an associative array (non-numeric keys) with a numeric-keyed array (the push operation), PHP MUST add the numeric key to your pushed item: You can't have an element in an array WITHOUT a key.
Then, since JS doesn't allow actual JS arrays ([]) to have non-numeric keys, the whole thing has to get converted into an object ({}).
What you probably want is something more like:
while($row = ...) {
... build $a ...
array_push($row['users'], $a);
instead.
Why don't you in stead array_push($row,$a) try following:
<?php
include("DbConnect.php");
$connection=new DbConnect();
$sth = mysqli_query($connection->_con,"SELECT * FROM account WHERE ac_id='1'");
if($sth){
$rows = array();
while($row = mysqli_fetch_assoc($sth)){
$users = mysqli_query($connection->_con,"SELECT user.user_id, user.name, user.email, ac_detail.ac_id, ac_detail.amount FROM user,ac_detail WHERE ac_detail.ac_id='1' AND user.user_id=ac_detail.user_id");
$usersArray = array();
while($userRow = mysqli_fetch_assoc($users)){
$usersArray[]=$userRow;
}
// here comes the change
// $a = array("users"=>$usersArray);
// //$row["user"]=$usersArray
// array_push($row,$a);
$row['users'] = $usersArray;
$rows[] = $row;
}
echo json_encode(array('data'=>$rows));
}else{
echo json_encode(array('message'=>'error - 2'));
}
This should work. Dont have sample data to test it.

Advancing the "cursor" in an associative array PHP

I have an associative array like such:
$arr = array('format' => 'A4', 'coulor' => 'red', 'height' = > '30');
I would like to use it in an mysql query like such:
reset($arr);
$first_key = key($arr); // get the first key of the array
$sql = "// sql query here...";
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_assoc($result))
{
echo $row[$first_key]; // will echo out the content of a table field
}
How to advance the cursor of this associative array so I can echo out the content of the next column in the mysql table
If you really need to use the keys of your $arr then just do:
while($row = mysqli_fetch_assoc($result))
{
foreach($arr as $key=>$v)
echo $row[$key];
}
Otherwise you can simply use mysqli_fetch_row() In this way your keys are integers, and you can get the next by doing:
while($row = mysqli_fetch_row($result)) {
echo $row[0]; // will echo out the content of a table field
echo $row[1]; // will echo out the content of a table field
}

Append non numeric key-values to an array

Trying to return a DB resultset as an array in my DAO:
I want to append string key-values to the array $retval in the below code. However, the array keeps getting overwritten each iteration instead of being appended to.
So at the end of the loop, I end up with 1 key-value instead of n pairs (n rows retrieved from the database). What am I doing wrong?
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
foreach($columns as $var) {
$retval[$var]=$row[$var];
}
}
var_dump($retval);
$retval ends up as ["name"=>"Japan","capital"=>"Tokyo"] instead of the expected ["name"=>"Korea","capital"=>"Seoul"...."Japan"=>"Tokyo"] where columns are name and capital.
I'd have to see what your columns are, but shouldn't it be:
$retval = array();
while ($row = mysql_fetch_assoc($result)) {
$retval[ $row['country'] ] = $row['capital'];
}
It is because you are overwriting the same value (column name here.) Something like:
$retval['a'] = 1;
$retval['a'] = 2;
// ...
Instead use:
$retval[] = $row[$var];
HTH.

Categories