Create multidimensional array from a loop in PHP - php

I'm trying to create a multidimensional array from some content I have in a database.
At the moment, I have this, which creates an array:
$js_arr = [];
while($row = mysqli_fetch_array($r->query)){
$js_arr[] = $row['todo_content'];
}
Returning:
Array ( [0] => first [1] => tester [2] => first item [3] => Hello!)
However, I also need to grab the $row['todo_id'].
I've tried this, but it only creates an array for the first row:
$js_arr = [];
while($row = mysqli_fetch_array($r->query)){
$js_arr['todo_content'] = $row['todo_content'];
$js_arr['todo_id'] = $row['todo_id'];
}
Returning:
array(2) { ["todo_content"]=> string(3) "hey" ["todo_id"]=> string(2) "90" }
I'm still learning PHP so any help or pointers would be much appreciated.

Two good options:
If the todo_id is unique, let it be the key:
$js_arr[$row['todo_id']] = $row['todo_content'];
Or for a multi-dimensional array, needed if you have more than just todo_content:
$js_arr[] = array('todo_content' => $row['todo_content'], 'todo_id' => $row['todo_id']);

Simply nest the items you want inside an array:
$js_arr[] = [
'todo_content' => $row['todo_content'],
'todo_id' => $row['todo_id']
];
The $js_arr[] part cannot ever be anything else, because any other syntax will not unconditionally add an element to the end of your multidimensional array.

I would use the ID as the key:
while($row = mysqli_fetch_array($r->query)){
$js_arr[$row['todo_id']]['todo_content'] = $row['todo_content'];
}
Or - assuming you need everything that you get from the database:
while($row = mysqli_fetch_array($r->query)){
$js_arr[$row['todo_id']] = $row;
}
What you can replace with (no loop, but no ID's as keys):
$js_arr = mysqli_fetch_all($r->query);

Related

PHP instead of printing one array with a few elements, prints number of arrays

I'm playing around with PHP from a couple of months now, I'm trying to print the result of a select query in form of an array, but the issue is that my code's logic isn't correct, and I'm unable to find the problem. Most probably I'm using loops in an inappropriate manner.
I'm using arrays for the first time.
I've done a bit of research, but to no avail.
PHP code:
$data = array();
$selectquery1result = mysqli_query($sqlconnection , $selectquery1);
if (mysqli_num_rows($selectquery1result) > 0) {
while($row = mysqli_fetch_array($selectquery1result)) {
$data[] = $row['U_id'];
print_r($data);
}
}
I've defined $sqlconnection and $selectquery1.
My SQL Server has two records for $selectquery1.
Actual results
Array
(
[0] => 10
)
Array
(
[0] => 10
[1] => 10
)
I don't know why but the number of arrays is the same as the number of rows that should be returned for $selectquery1.
Expected results
Array
(
[0] => 10
[1] => 10
)
So, any help with that would be very helpful for me.
Thanks in Advance!
You are printing your array each iteration of a while loop. Instead you should put your print_r statement outside the loop body.
$data = array();
$selectquery1result = mysqli_query($sqlconnection , $selectquery1);
if (mysqli_num_rows($selectquery1result) > 0) {
while($row = mysqli_fetch_array($selectquery1result)) {
$data[] = $row['U_id'];
}
print_r($data);
}

PHP build json from a dynamic number of arrays

I have a dynamic number of pages in my web project. It depends on data from the database. I may have 1 page or 10 pages. I put the data selected on each page in session, and finally want to build an array. At the moment I am building JSON from 4 arrays. (In session all the keys are level + int in ascending order. If session x is missing I don't have any data on 6+ levels)
$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();
if (isset($_SESSION['level1'])) {
$level1 = $_SESSION['level1'];
}
//the same for 3 more levels in session
$array = array(
"first" => ($level1),
"second" => ($level2),
"third" => ($level3),
"fourth" => ($level4)
);
json_encode($array);
Example of output of the json_encode($array):
{"first":["1","2"],"second":["4","6","8","9"],"third":["13","14","17","18"],"fourth":["33","34","35","36"]}
I tried to check how would json_encode work with array_push(), but I get an array of JSON objects instead of a single json object.
$result = array();
array_push($result, ["key1" => $_SESSION["level1"]]);
array_push($result, ["key2" => $_SESSION["level2"]]);
array_push($result, ["key3" => $_SESSION["level3"]]);
echo json_encode($result);
and the output:
[{"key1":["1","2"]},{"key2":["4","5","6"]},{"key3":["13","14","15"]}]
I will make everything iteratively, but I want to know if it is possible to make a single JSON object instead of array of JSONs. Thanks!
You can just add the keys to the array without any need for a function.
$result = array();
$result["key1"] = $_SESSION["level1"];
$result["key2"] = $_SESSION["level2"];
$result["key3"] = $_SESSION["level3"];
echo json_encode($result);

How to use array_push to multidimensional arrays?

I was wondering how to use array_push to multidimensional arrays?
I have a multidimensional array, in which i'm trying to push more values from another array. The multidimensional you can see below.
$userList[] = array(
"aid" => $searchrow['aid'],
"name" => $searchrow['name'],
"info" => $searchrow['info'],
"rental" => $searchrow['rental'],
"rentalfirm" => $searchrow['rental_firm'],
"acqprice" => $searchrow['acq_price'],
"renprice" => $searchrow['ren_price'],
"serial" => $searchrow['serial']);
}
Second set of arrays:
mysql query... blaa blaa
$assetInuseID[]=$searchrowinuse['asset_usage_id'];
$inuse[]=$searchrowinuse['in_use'];
$total[]=$searchrowinuse['total'];
What I'm tryin to accomplice is something like below.
$i = 0;
while(!empty($userList[$i][aid]))
{
if($userList[$i][aid] == $assetInuseID[$i])
{
array_push($userList[$i][inUse], "$inuse[$i]");
array_push($userList[$i][total], "$total[$i]");
}
$i ++;
}
So, I want to create: inUse- and total-cells in the allready existing $userList[][] and populate them with with the allready existing values of $total[$i] and $inuse[$i] when the $userList[$i][aid] matches $assetInuseID[$i].
I hope someone understands me, my explanation was a little bit confusing...
Thank you very much.
You can use the following,
$userList[$i]["inUse"] = "$inuse[$i]";
Remember array_push — Push one or more elements onto the end of array and not create an index.

While loop in foreach loop not looping correctly

I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.
$results = array();
foreach($this->columns as $column){
$current = array();
while($row = mysql_fetch_array($this->results)){
$current[] = $row[$column];
print_r($current);
echo '<br><br>';
}
$results[$column] = $current;
}
print_r($results);
return mysql_fetch_array($this->results);
This works, but the while loop only works on the first column. The print_r($results); shows the following:
Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )
Can anybody shed some light?
Thanks in advance!
It's because you already fetched every row, and the internal pointer is at the end.
The next while, mysql_fetch_array() will immediately return false.
You can reset the pointer to the first row:
mysql_data_seek($this->results, 0);
Put this just before
while($row = mysql_...
I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:
foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value
}

Change the array KEY to a value from sub array

This is the set of result from my database
print_r($plan);
Array
(
[0] => Array
(
[id] => 2
[subscr_unit] => D
[subscr_period] =>
[subscr_fee] =>
)
[1] => Array
(
[id] => 3
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 90,1000
)
[2] => Array
(
[id] => 32
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 150,1500
)
)
How can I change the $plan[0] to $plan[value_of_id]
Thank You.
This won't do it in-place, but:
$new_plan = array();
foreach ($plan as $item)
{
$new_plan[$item['id']] = $item;
}
This may be a bit late but I've been looking for a solution to the same problem. But since all of the other answers involve loops and are too complicated imho, I've been trying some stuff myself.
The outcome
$items = array_combine(array_column($items, 'id'), $items);
It's as simple as that.
You could also use array_reduce which is generally used for, well, reducing an array. That said it can be used to achieve an array format like you want by simple returning the same items as in the input array but with the required keys.
// Note: Uses anonymous function syntax only available as of PHP 5.3.0
// Could use create_function() or callback to a named function
$plan = array_reduce($plan, function($reduced, $current) {
$reduced[$current['id']] = $current;
return $reduced;
});
Note however, if the paragraph above did not make it clear, this approach is overkill for your individual requirements as outlined in the question. It might prove useful however to readers looking to do a little more with the array than simply changing the keys.
Seeing the code you used to assemble $plan would be helpful, but I'm going assume it was something like this
while ($line = $RES->fetch_assoc()) {
$plan[] = $line;
}
You can simply assign an explicit value while pulling the data from your database, like this:
while ($line = $RES->fetch_assoc()) {
$plan[$line['id']] = $line;
}
This is assuming $RES is the result set from your database query.
In my opinion, there is no simpler or more expressive technique than array_column() with a null second parameter. The null parameter informs the function to retain all elements in each subarray, the new 1st level keys are derived from the column nominated in the third parameter of array_column().
Code: (Demo)
$plan = array_column($plan, null, 'id');
Note: this technique is also commonly used to ensure that all subarrays contain a unique value within the parent array. This occurs because arrays may not contain duplicate keys on the same level. Consequently, if a duplicate value occurs while using array_column(), then previous subarrays will be overwritten by each subsequent occurrence of the same value to be used as the new key.
Demonstration of "data loss" due to new key collision.
$plans = array();
foreach($plan as $item)
{
$plans[$item['id']] = $item;
}
$plans contains the associative array.
This is just a simple solution.
$newplan = array();
foreach($plan as $value) {
$id = $value["id"];
unset($value["id"]);
$newplan[$id] = $value;
}

Categories