Error in adding data to multi-dimensional array in php - 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;

Related

How to change this array key based on this mysql result

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

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

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

making three dimensional array that has an unknown amount of arrays inside

I'm trying to store data from a table, and I do not know how many lines will be in said table. My idea was to make a main array called data, a sub array for each line with just numeric labels (1,2,3,etc) and then inside each of those would be the actual data from each line, so it would be like this:
data
->1
->item1
->item2
->item3
->2
->item1
->item2
->item3
->3
->item1
->item2
->item3
ETC. I know how to work with multidimensional arrays and I know there are easy ways to accomplish this in java, but I can't for the life of me figure out how to do it in php.
To keep on adding to an array simply use the following code:
$myArray[] = 'another value';
Notice the [] this tells php to add another value to the array (without removing previous elements)
See here for a quick tutorial on mutidimensional arrays:
http://webcheatsheet.com/PHP/multidimensional_arrays.php
And this:
http://www.developerdrive.com/2012/01/php-arrays-array-functions-and-multidimensional-arrays/
Try,
foreach($rows as $v) {
$data[] = array($v['item1'], $v['item2'], $v['item3']);
}
To map mySQL data to a multidimensional array:
$query = mysql_query("SELECT * FROM table WHERE uid = '1' ORDER BY id DESC");
$results = array();
$i = 0;
while($line = mysqli_fetch_array($query, MYSQL_ASSOC)){
$results[$i] = $line;
$i++;
}

array to string conversion error, need to explode and then implode

I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);

Categories