Need help pulling data out of mysql into a multidimensional array - php

I am pulling data out of a data base. As I seem to be having trouble with arrays and multidimensional arrays I need some help.
In the database I am pulling the following information:
id, platoon, name, position, status
I need to put all of this into an array.
As there are over 150 names, with many holding the same position.
here is the code I am using:
$sql='SELECT id, position, platoon, name, status FROM ost_platoon_assignments';
$users=db_query($sql);
$num=db_num_rows($users);
while ($row = db_fetch_array($users)) {
$info = array(
$row['position'] => array(
$row['platoon'] => array("name" =>$row['name'], "status" => $row['status']),
),
);
}
I want to list via a table by those in a particular position:
example:
<table border="1">
<?
foreach ($info as $position => $names) {
echo "<tr>";
echo "<td> {$position} </td>";
foreach ($names as $name) {
if ($name[name] =="") {$name[name] = "Vacant"; }
echo "<td class=\"status{$name[status]}\"> {$name[name]} </td>";
}
echo "</tr>";
}
?>
</table>
What am I missing? When I run this it only gives me the last entry.
Thanks for your help

You are overwriting the value of $info with each iteration of your while statement.
If you want to store all your data in array structure like this:
$info = array(
'general' => array(
array( /* general 1 */ ),
array( /* general 2 */ ),
array( /* general 3 */ )
),
'colonel' => array(
array( /* colonel 1 */ ),
array( /* colonel 2 */ ),
),
// .....
)
Then use a process like the following: (Note I'm using PDO, you could also use PHP'S mysqli, but use one of these instead of PHP's mysql library which is deprecated).
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
$result = $conn->query('SELECT id, position, platoon, name, status FROM ost_platoon_assignments');
$info = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$info[$row['position']][] = $row;
}
You can then loop through each user by position like this
foreach ($info as $position => $users) {
foreach ($users as $user) {
// ....
}
}

It should be
$info[] = array( ..... );
^^-----
instead. Right now you're continually OVERWRITING $info with every result row being retrieved. The [] notation will PUSH the new row onto the $info array, instead of simply replacing what was there previously.

Related

renaming array using foreach on controller and view:

I'm having a problem, I tried renaming my $query->result_array() using foreach on my controller and called it in view using another foreach to display the result from $query->result_array();
Here's how I did it.
My controller:
I have this user-defined function named logs(), I have a query inside and used $query->result_array() to get the results. Then I renamed it using foreach{} like this code below:
$result = array();
foreach ($query->result_array() as $row) {
$result = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;
Then I created another user-defined function named filtered_logs() to filter the result from logs() *I filtered it because I have multiple tables to LEFT JOIN it with.
$filtered = array();
$logs = $this->logs();
if ($logs['status'] == "ok") {
$query = $this->db->query("SELECT * FROM table a
LEFT JOIN table b
ON a.image = b.image
LEFT JOIN ....ON...
WHERE a.id = '".$logs['id']."'");
foreach ($query->result_array() as $row){
$filtered = array(
"path" => $row['path'],
"grade" => $row['grade'],
"time" => $logs['time'],
);
}
}
Sending these results to view I used this method, placed on the index of the controller.
$data['logs'] = $this->filtered_logs();
$this->load->view('pages', $data);
Then displayed it on view using these codes:
<?php
foreach ($logs as $row) {
echo $row['id']." </br>";
echo $row['status']." </br>";
echo $row['time']." </br>";
}
?>
but when I do use this way of handling result_array, it gives me an error saying " Illegal string offset '' "
Can someone help me or tell me if there's another way of displaying the results of my queries?
I guess you are missing "[]" after $result array where you are feeding data in it in for each loop and it is causing this error.
It should be like this:
$result = array();
foreach ($query->result_array() as $row) {
$result[] = array(
"id" => $row['id'],
"name" => $row['name'],
"status" => $row['status'],
"time" => $row['time']
);
}
return $result;
This is just an other way of displaying the results try it.
<?php
foreach ($logs as $row) {
echo $row->id." </br>";
echo $row->status." </br>";
echo $row->time." </br>";
}
?>

How to properly encode a multi-dimensional array in php [duplicate]

This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 7 years ago.
I am trying to properly create and encode and array using json_encode php function. The array i am trying to encode is $myarray . From my code if do
$myarray = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
then
echo json_encode($myarray) ; // this works but only one item is pushed to my array
if i do
$myarray[] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array
result is nothing.
what i am missing ?
see full code below on what i have so far done.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
//Push values to my array
$myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
//
}
//Then try to encode $myrray but this fails
$jsonstring = json_encode($myarray);
if ($jsonstring!==false)
{
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
///////////////////////
/////////////////////////
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
please help. thank you.
The right way to create the array would be like this:
$myarray = array(
array(
'name' => 'bla',
'id' => 1
), array(
'name' => 'blas',
'id' => 2
)
);
This part of your code is perfectly fine.
$data = array() ; //create new empty array
//loop through the array
foreach($myarray as $keys => $h)
{
$data [] = $h;
}
//encode
echo json_encode($data) ; //this fails silently
If you run the code, it works perfectly fine:
[{"name":"bla","id":1},{"name":"blas","id":2}]
Your foreach() loop creates a new array $data with the same entries (also arrays) as the $myarray contains. So, you could directly encode $myarray like this:
<?php
$myarray = array(
array('name' =>' Agrolait', 'id' => 6 ),
array('name' => 'Agrolait, Michel Fletcher', 'id' => 31 ),
array('name' => 'Agrolait, Thomas Passot', 'id' => 30 )
);
$jsonstring = json_encode($myarray);
if ($jsonstring!==false) {
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
?>
Which produces this JSON string:
[{"name":" Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}]
json_encodereturns the value FALSE if something went wrong, and the encoded string else. If you check the result from it you at least know when it fails.
Thanks for your suggestion have solved this. My string data was not properly encoded using utf-8 as suggested by http://nl3.php.net/manual/en/function.json-encode.php. Check my answer below
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
$myarray [] = array('name' =>utf8_encode($value['display_name']->scalarval()),'id' => utf8_encode($value['id']->scalarval())) ;
//
//array_push($better, $myarray) ;
}
//echo '<pre>';
//print_r($myarray) ;
//echo '</pre>';
echo json_encode($myarray);
exit;
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>

Create multidimensional array from rows of data

I have a database with project entries. Each entry has a project title, datestamp, the user who entered it, and a comment. I am trying to format this data as JSON for reporting and charts.
I want an array for each project name, and inside that array an array for each entry.
I've tried several approaches but I haven't had much luck yet.
if ($result = $mysqli->query("SELECT * FROM project_entries"))
// WHERE WEEK(date) = WEEK(current_date) ORDER BY project_name
{
while ($row = mysqli_fetch_array($result)) {
$entry_array = array();
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array (
'comment' => $comment,
);
$row_array['entries'] = $entry;
if ( !in_array($row['project_name'], $projects, false ))
{
array_push($projects, $row_array);
}
}
}
Outputs:
[
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing"
}
},
{
"project_name": "Logo Design",
"entries": {
"comment": "Created some stuff"
}
},
While I want:
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing",
"comment": "Created some stuff"
}
}
This should do the trick. You can use the project name as an array key. In order to prevent the string keys from showing up in your output array, you can use array_values to convert them to numeric keys.
$projects = array();
while ($row = mysqli_fetch_array($result)) {
$projects[$row['project_name']]['project_name'] = $row['project_name'];
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
}
echo json_encode(array_values($projects));
What was going wrong with your previous code:
if ($result = $mysqli->query("SELECT * FROM project_entries")) {
while ($row = mysqli_fetch_array($result)) {
$entry_array = array(); // This does not appear to be used
// With each iteration of the while loop, you create a new array of
// project information (project name and entries array with one comment)
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array ('comment' => $comment);
$row_array['entries'] = $entry;
// The $projects array is an array of arrays, but $row['project_name'] is
// a string. Checking if this string is in an array of arrays will always
// be false, so the array_push should always execute.
if (!in_array($row['project_name'], $projects, false )) {
// Adds the new project array to the projects array
array_push($projects, $row_array);
}
// This is not producing what you want because you are adding a new
// array to $row_array each time the loop runs
}
}
Why the code I suggested works:
$projects = array(); // Empty array to hold all the projects
while ($row = mysqli_fetch_array($result)) {
// Using the project name from the database as an array key in the array we are
// constructing keeps the projects unique in that array.
// The first time a new project name occurs, this will create a new sub-array
// within $projects with project_name => the new project name. This value will
// be overwritten on subsequent occurrences of the same project name.
$projects[$row['project_name']]['project_name'] = $row['project_name'];
// For each iteration, this will add a comment to the 'entries' array in the
// project array with the key $row['project_name'].
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
// For example, with the first iteration of the array we create the following:
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'] ] ]
//
// with the second iteration, the project name is overwritten (with same project name)
// and another comment array is added to the entries array
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'],
// 1 => ['comment' => 'Created some stuff'] ] ]
}
// If you just did echo json_encode($projects), you would not get the format you want,
// because of the string keys. Try it without the array_values() to see what I mean.
echo json_encode(array_values($projects));
Maybe something like that?
Use project id to build target array.
while ($row = mysqli_fetch_array($result) {
if (!isset($projects[$row['id']]))
{
$projects[$row['id']] = [
'project_name' => $row['project_name'],
'entries' => [],
];
}
$projects[$row['id']]['entries'][] = [
'comment' => $row['comment'],
];
}

Storing values of multidimensional array into variables

I have the following code:
$res = $db->getArticles($db);
$hey = print_r($res, TRUE);
echo $hey['0'];
Here is the code for $db->getArticles:
public function getArticles() {
$array = array();
try {
$sth = $this->db->prepare("SELECT * FROM posts ORDER BY id");
$sth->execute();
foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row) {
$array[] = $row;
}
return $array;
} catch (Exception $e) {
}
}
The logic is that the function queries the database and puts everything into an array. The number of rows in the table will always be pretty low, so performance isn't an issue.
The following is the output of the first code snippet above:
echo $hey['0']; // prints "A" (without the quotes).
echo $hey['1']; // prints "r"
echo $hey['2']; // prints "r"
echo $hey['3']; // prints "a"
echo $hey['4']; // prints "y"
As you can see, it spells out the word "Array."
echo $hey prints the following:
Array ( [0] => Array ( [id] => 1 [author] => 0 [content] => This Is a Test [publication_date] => 1380380992 ) )
My end goal is to store each individual value into a variable and do something with it. This would all happen inside a for loop which runs on the array so I can get information from each row.
What am I doing wrong?
$hey = print_r($res, TRUE);
This will return a string that gives the info of the array $res. If you echo it, you should expect to see the same as what print_r($res); displays, as you've shown. $res is already an array of your query data, so loop over that.
foreach($res as $row) { //row loop
foreach($row as $col) { //column loop
//do something
}
}
$array = array( array( ID => 1,
author => 0,
content => "This Is a Test",
publication_date => 1380380992
)
);
echo $array['0']['author'];
This works for me...
just echo echo $array['0']['author']; and replace author by the field you need.

PHP - Help building a multi dimensional array

I would like to know how to get the values into this array. Can someone please help?
Each box whether it is the in or outbox should only be listed once and then have multiple ids associated with them. I need to be able to tell which id came from what box. The ids that are in the array are only samples.
$arr =
array(
'Inbox'=> array('id' => array(8, 9, 15)),
'Outbox'=> array('id' => array(8, 9, 15))
);
Thanks
$inbox = $db->Query("SELECT * FROM mail_inbox");
$outbox = $db->Query("SELECT * FROM mail_outbox");
foreach($inbox as $key => $array)
{
$output['Inbox']]['id'][] = $array['msg_seq'];
}
foreach($outbox as $key => $array)
{
$output['Outbox']]['id'][] = $array['msg_seq'];
}
print_r($output);
This will give me the db fields from the inbox but I have no idea how to get the outbox in there as well. I also get undefined index for ['Box']
Now that I know what you are saying, to input stuff, do something like this to input it into the array:
$ID = 9;
$box = "Inbox";
$arr[$box]['id'][] = $ID;
or
$IDs = array(9,5,13);
$box = "Inbox";
$array = array($box => $IDs);
or if you were getting it from a Database
$dbarray[0] = array('ID' => 9,
'Box' => 'Outbox');
foreach($dbarray as $key => $array)
{
$output[$array['Box']]['ids'][] = $array['ID'];
}
Multi deminsional arrays
The key or index is the first bracket
$array[key]="foo"
is the same as
$array = array('key' => 'foo');
if there is a second bracket, it of the array inside the value part of an array. IE
$array['key']['key2'] = "bar";
is the same as
$array = array('key' => array('key2' => 'bar'));
Basically, multideminsional arrays are just arrays inside of arrays.
foreach($arr as $box => $array)
{
echo $box;
// $box = The Box
foreach($array['ids'] as $ID)
{
echo $ID . ",";
// $ID = The ID
}
echo "<br>";
}
Sample:
Outbox 9,13,15,
Inbox 9,13,15,
This goes through each box, echos the box name, and each ID inside of the box, and echos the ID.
To access only one box
foreach($arr['Inbox'] as $ID)
{
echo $ID . ",";
}
Sample Output:
9,13,15,

Categories