How to change this array key based on this mysql result - php

I have this code and query also.
$id_user = $this->current_user->id;
$query_perusahaan = "SELECT
default_perusahaan.id_perusahaan,
default_perusahaan.nama_perusahaan
FROM
default_users
INNER JOIN default_user_perusahaan ON default_user_perusahaan.id_default_user = default_users.id
INNER JOIN default_perusahaan ON default_perusahaan.id = default_user_perusahaan.id_default_perusahaan
WHERE default_users.id = $id_user";
$query_perusahaans = $this->db->query($query_perusahaan)->result_array();
$list_per = array();
$list_per[null] = "Tidak memakai perusahaan";
foreach ($query_perusahaans as $item => $nama) {
$list_per[$item] = $nama;
}
print_r($list_per);
die();
This is the result :
The result what I expect is the id_perusahaan to become the array key.
What am I doing wrong? :(

Replace
$list_per[$item] = $nama;
With
$list_per[$nama['id_perusahaan']] = $nama['name_perusahaan'];

Instead of looping the array, you can use array_column
$list_per = array_column($query_perusahaans, null, "id_perusahaan");
The third argument sets the key names.
That means array_column will return the array with no specific column (null), but change the keys to "id_perusahaan".
That results in the array being associative
Or if you want the array to be flat:
$list_per = array_column($query_perusahaans, "name_perusahaan", "id_perusahaan");

Related

Why is array_unique not working in this situation

I have a column that contain integer values. I join all columns by doing
"SELECT GROUP_CONCAT(column) AS column"
Then I build an array doing
while ($row = $result->fetch_assoc()){
$employees[] = $row['column'];
}
print_r($employees) returns Array ( [0] => 1,2,3,4,68,25,1 )
So I want to remove the duplicate 1 and for that I use array_unique
print_r(array_unique($employees));
This still brings back Array ( [0] => 1,2,3,4,68,25,1 )
What am I doing wrong here
Solution at SQL side:
SELECT GROUP_CONCAT(DISTINCT column) AS column
if you want an ordered list:
SELECT DISTINCT column ORDER BY Column
and then store all rows by
while(...) $employees[] = $row['column'];
The problem is that you are trying to use array_unique() on a string, which won't really do anything.
You can break this string into an array by using the explode() function.
$unique = array_unique(explode(',', $employees[0]);
Alternatively, you could just check inside your loop if a value has already been put into an array using in_array().
while ($row = $result->fetch_assoc()){
if(!in_array($row['column'], $employees)) {
$employees[] = $row['column'];
}
}
Just use the array_map function. And map all value with intdiv function
$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);

Is this the correct PHP Syntax for adding an associative array to an existing associative array.

I have three variables retrieved from a database and I would like the first variable to be the key for the second variable and for that second variable to be the key for the third variable. In essence a two-dimensional array.
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$unit_id = $row['id'];
$unit_code = $row['unit_name'];
$unit_description = $row['unit_description'];
$units = [$unit_id => $unit_code];
$units += [$unit_code => $unit_description];
}
return $units;
You can simply make like this
<?php
$unit_id = 'id';
$unit_code = 'unit_name';
$unit_description = 'unit_description';
$units[$unit_id] = [$unit_code=>$unit_description];
//$units[$unit_id][$unit_code] = $unit_description;
print_r($units);
?>
Live demo : https://eval.in/880865
Yess you can do this.
$array = [
'data' => 'my data'
];
now you can do this simply
$array['anotherArray'] = $anotherArray;
If "id", "unit_name" and "unit_description" are respectively the first, second and third value of the database, this is the code:
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$units[$row['id']][$row['unit_name']] = $row['unit_description'];
}
return $units;
If array consists of key, value parts (associative arrays), which your case is like that, you just need to:
$data[$key] = $value;
So in your case it would be:
$units[$unit_code] = $unit_description;
If your arrays' keys are indexed, then using array_push can do the job too:
array_push($units, $unit_description);

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
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[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

Preserve the insert order in a PHP array

I have a PHP page used by an Ajax call that I want to return an ordered list of items as JSON. However whichever field I use in the query's 'order by' clause the array is always ordered by its key, the ID field.
Is there a way to preserve the insert order of each item in the PHP array?
This is the code that generates the JSON array:
$Soggetti = array();
while($row = $db->fetch_array($query))
{
$Soggetti[$row['ID']] = array();
$Soggetti[$row['ID']]['Denominazione'] = $row['Denominazione'];
$Soggetti[$row['ID']]['Indirizzo'] = $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
$Soggetti[$row['ID']]['Superficie'] = $row['Superficie'];
$Soggetti[$row['ID']]['Lat'] = $row['Lat'];
$Soggetti[$row['ID']]['Lng'] = $row['Lng'];
$Soggetti[$row['ID']]['Tipologia'] = $row['Tipologia'];
$Soggetti[$row['ID']]['CodiceIscrizione'] = $row['CodiceIscrizione'];
$Soggetti[$row['ID']]['Visitato'] = intval($row['Visitato']);
}
echo json_encode($Soggetti)
If the problem lies in where the JSON is interpreted, in the client, you can use this syntax to return a JSON array (enclosed in []) instead of a JSON object (enclosed in {}).
echo json_encode(array_values($Soggetti));
You are building a 2 dimensional array with the key on first dimension being the id. Assuming id is numeric you will end up with nested objects in JSON, with the key of top level being the numerical id values. The problem here being that object properties have no guarantee of order.
To get the order of the query results, simply build a 1-D array inside your result set loop like this:
$tempArray = array();
$tempArray['ID'] = $row['ID'];
$tempArray['Denominazione'] = $row['Denominazione'];
$tempArray['Indirizzo'] = $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
$tempArray['Superficie'] = $row['Superficie'];
$tempArray['Lat'] = $row['Lat'];
$tempArray['Lng'] = $row['Lng'];
$tempArray['Tipologia'] = $row['Tipologia'];
$tempArray['CodiceIscrizione'] = $row['CodiceIscrizione'];
$tempArray['Visitato'] = intval($row['Visitato']);
$Soggetti[] = $tempArray;
The will encode to JSON as an array of objects with the array numerically indexed from 0 based on order in result set.
You need an ORDER BY clause of your MySQL statement.
In this case you want to order by your id, and in ascending order, so;
SELECT * from your_table ORDER BY id ASC
Reference: MySQL Sorting
The problem may lie in your mysql query, try:
select * from table_name order by ID asc

Error in adding data to multi-dimensional array in php

I want to read data from a data base, and put it in multi-dimensional array.
I don't know number of rows that will come from data base, and when i try to add new row to the multi-dimensional array i have the following error
Warning: array_push() [function.array-push]: First argument should be an array in C:\AppServ\www\web\commands\changeservice.php on line 101
and this is the code i have
function preparenewservices()
{
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices[count($newservices)], $newservice);
}
}
try this:
array_push ($newservices, $newservice);
instead of:
array_push ($newservices[count($newservices)], $newservice);
because now you pass to the first argument of array_push an integer value not an array
Thats because $newservices[count($newservices)] is not an array
Read docs here array_push
Just to fix the error you can do this
$newservices[count($newservices)] = array();
array_push ($newservices[count($newservices)], $newservice);
Try to replace this code
array_push ($newservices[count($newservices)], $newservice);
with
$newservices[count($newservices)] = $newservice;
The simplest way of adding an element/array to another array is this:
$newservices[] = $newservice;

Categories