PHP array : simple question about multidimensional array - php

i've got a SQL query which returns multiple rows, and i have :
$data = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
which is perfect, but only if my query returns one row.
i tried that :
$data = array();
$data[$row['nom']]["nom"] = $row['nom'] ;
...
$data[$row['nom']]['average'] = "$moyenne_ge";
in order to have :
$data[brand1][nom] = brand1
$data[brand1][average] = 150$
$data[brand2][nom] = brand2
$data[brand2][average] = 20$
...
but when i do : json_encode($data)
i only have the latest JSON object instead of all JSON object from my request as if my array has only one brand instead of 10.
I guess i did something stupid somewhere.
Thanks for your help

I'd guess that your line:
$data = array();
Is initializing the array on each iteration of your loop. You aren't accumulating more than one row of data.

I guess something like this should work for you:
$resource = mysql_query("YOUR QUERY");
$results = array()
while($result = mysql_fetch_assoc($resource)) {
$results[$result['brand']] = array(
'nom' => $result['nom'],
'prix' => $result['rapport'],
'average' => $moyenne_ge
);
)
$results now contains all the rows from the query indexed by brand. Ask in comments if this wasn't what you're looking for.

If I am reading you right, you should just have to do something like this:
$data[] = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
(notice the [])
This should append each array onto $data instead of overwriting the contents.

Related

How to insert_batch() in Codeigniter 3 with "inconsistent?" array associative

I've Googling but the results doesn't match with my problem.
so, i have this array:
$data1 = array(
'DRAWING_NO'=>123,
'NO_PLANNING'=>321,
);
$data2 = array(
'DRAWING_NO'=>456,
'NO_PLANNING'=>654,
'ON_CREATE'=>date('Y-m-d H:i:s')
);
then i'm doing insert_batch()
$this->db->insert_batch('tb_drawing_lvl',array($data1,$data2));
but i got error
yes, i knew it, because in $data1 i don't give 'ON_CREATE' key. but i want insert them to my table and the result is like this
How to do that using insert_batch?
I ended up applying the below logic.
Actually What I did is created a separate array and and went through the loop of the existing array and checked if the necessary key and values exists, if not i have added those keys and performed batch insert with the all the keys required!
$data = array(
array(
'DRAWING_NO' => 121 ,
'NO_PLANNING' => 123
),
array(
'DRAWING_NO'=>456,
'NO_PLANNING'=>654,
'ON_CREATE'=>date('Y-m-d H:i:s')
)
);
$row_arr = array();
foreach($data as $row){
$temp = array(
'DRAWING_NO' => isset($row['DRAWING_NO']) ? $row['DRAWING_NO'] : NULL,
'NO_PLANNING' => isset($row['NO_PLANNING']) ? $row['NO_PLANNING'] : NULL,
'ON_CREATE' => isset($row['ON_CREATE']) ? $row['ON_CREATE'] : date('Y-m-d H:i:s')
);
array_push($row_arr,$temp);
}
$this->db->insert_batch('test',$row_arr);

sql result as array of arrays

i'm trying to format the output of a sql query as an array of arrays, for using the gannti class graph tool on my sql data. I'm not very experienced(outside industrial plc's), and can't seem to find a solution to this particular problem despite lots of googeling.
The sql query i want to perform looks like this:
$query = "SELECT label, start, end from oppgaver ";
And the original array showed in the gannti class example is written like this:
$data = array();
data[] = array(
'label' => 'alarmkit',
'start' => '2013-08-01',
'end' => '2013-09-10'
);
$data[] = array(
'label' => 'Stekeovnskontroller',
'start' => '2013-08-22',
'end' => '2013-09-01'
);
$data[] = array(
'label' => 'Tull og fanteri',
'start' => '2013-09-02',
'end' => '2013-09-10'
);
And then you call the gantti to do it's thing:
$gantti = new Gantti($data, array(
'title' => 'Elektro',
'cellwidth' => 15,
'cellheight' => 35,
'today' => true
));
All works well, except for my unability to format the sql output to what i assume is an array of arrays so the gantti class can do its magic. I got it to show the first letter of each label in the sql database once, but that piece of mangled code i wrote should probably be forgotten :-)
Does anyone here have a idea about how to do this?
Update:
The last way i tried to get the data, by using msql_fetch_assoc.
Unfortunately i did not keep a record of the different approaches i made.
I've also tried several examples i found on using mysql_fetch_array, and mysql_fetch_row.
$query = "SELECT label, start, end from oppgaver ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row[0]);
}
Use $row to push in array in place of $row[0]
As given below
while ($row = mysql_fetch_assoc($result)) {
array_push($data, $row);
}

Selecting variable and storing into multi-dimentional array

I understand how multi-dimentional array works but iam new to it.
eg.
$arrayAns = array( subject => "he"),
array( subject => "I"),
array( subject => "they");
What I am trying to do is, get a variable from database and store it in the array.
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
$arrayAns = array( subject => "$rows")
Is that the way to do it?
Try this:
If the results from database are stored in rows:
$newArray = array();
foreach($rows as $key=>$value) {
$newArray[] = $value;
}
Here, all the variables in $value would be stored into the newArray.
Also, see array_push
Almost! But not quite
Here is how I would go about this:
$arrayAns = array(
array('subject' => "he"),
array('subject' => "I"),
array('subject' => "they")
);
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
$arrayAns[] = array('subject' => $rows);
Depending on what DB API are you using you may have an option to retrieve the data as a multidimensional array automatically. Check if $rows->toArray() is possible or something like that.
Otherwise not the most optimal, but easy and clean way is to foreach through your $rows list and build the array you want.
Btw, the array you have defined on top is defined like this in PHP:
$myArray = array(
array(
'subject' => 'he'
),
array(
'subject' => 'I'
),
array(
'subject' => 'they'
)
);
Change you syntax to look like this (you also had some syntax errors) -
// original multidimensional array
$arrayAns = array(
array( "subject" => "he"),
array( "subject" => "I"),
array( "subject" => "they")
);
// execute query
$query = "SELECT subject FROM #__wordBank ORDER BY RAND() LIMIT 1";
$db->setQuery($query);
$rows=$db->loadObjectList();
Now what we want to do is add another element to your original array. You can use the short hand [] syntax to push another element on to the top of the array.
$arrayAns[] = array('subject'=> $rows['subject']);
That line is functionally identical to this one -
array_push($arrayAns, array('subject'=> $rows['subject']));

An array of MySQL results...

What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.
Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push

problem with array and GoogChart

ok.. I know I can find help here :)
I am barely out of noobhood so be gentle :)
I'm trying to fetch data from a db and use it to call a pie chart in GoogChart so here is my problem... some code like db connections etc. is skipped to get to the point.
First we look at the array GoogChart uses to pass the info:
$data = array(
'8' => 6,
'3' => 3,
'9' => 2,
);
Now we look at how I am trying to do it pulling the data from a db:
//connect and query here
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// trimmed cuz I can't sort it out
$dat = "'$viewid' => $total_views,"; //problem likely here
}
$data = array(
$dat
);
When I echo the $dat, I get this:
'8' => 6,'3' => 3,'9' => 2,
So theoretically, it should work??? But noop :(
There may be a totally different way of doing this but I'm stumped... didn't take much to do it either lol.
What you're doing is creating an array with one element: "'8' => 6,'3' => 3,'9' => 2,".
Instead, you should be populating an array as you go:
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
$viewid=trim($row['id']);
$total_views=trim($row['views']);
// use the $viewid as the key and $total_views as the value
$data[ $viewid ] = $total_views;
}
Of course, you could also do (not certain if this could help you, but it is an option):
$data = array(); // create the array
while ($row=mysql_fetch_array($query)){
// use the $viewid as the key and $total_views as the value
$data[ trim($row['id']) ] = trim($row['views']);
}

Categories