if my code looks like...
$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
$list[] = $r;
}
print json_encode(array('list' => $list));
the result is...
list[0].id = '1', list[0].name = 'apple', list[0].color = 'red';
list[1].id = '2', list[1].name = 'banana', list[1].color = 'yellow';
...
It's fine, but i need additional infos in the list.
How can i extend the arrays and get something like:
list[0].id = '1', list[0].name = 'apple', list[0].color = 'red', list[0].taste = 'sour';
list[1].id = '2', list[1].name = 'banana', list[1].color = 'yellow', list[0].taste = 'sweet';
...
This does not work:
$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
$list[] = $r;
$list[]['taste'] = 'sweet'; //DOES NOT WORK
array_push($list,array("taste" => 'sweet')); //DOES ALSO NOT WORK
}
print json_encode(array('list' => $list));
Thank you!!!
Because $list[] = $value is the same as array_push($list, $value). There's no such thing as $list[]['key'].
You should add it to the $r variable instead, before you add it to $list:
while($r = $result->fetch_array()) {
$r['taste'] = 'sweet'; //DOES WORK!
$list[] = $r;
}
If you already have $list, you can simply loop through and add it:
foreach ($list as &$array) {
$array['taste'] = 'sweet';
}
unset($array); //remember to unset references
..or if you hate references:
foreach ($list as $key => $array) {
$list[$key]['taste'] = 'sweet';
}
You need an intermediate variable
$result = $mysqli->query("SELECT id, name, color FROM fruits");
$list = array();
while($r = $result->fetch_array()) {
$r['taste'] = 'sweet'; //Modify an existing array
$list[] = $r;
}
print json_encode(array('list' => $list));
Related
I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>
I'm trying to loop some array using foreach. This is the code which demonstrates what I'm doing
$q = "SELECT * "
."FROM ".TBL_FRUITSDETAILS."";
$fruitsdetails = $database->query($q);
$var = array();
while($line = mysql_fetch_assoc($fruitsdetails)){
$var[] = $line;
}
$q = "SELECT * "
."FROM ".TBL_NUMDETAILS."";
$numdetails = $database->query($q);
$var2 = array();
while($line2 = mysql_fetch_assoc($numdetails)){
$var2[] = $line2;
// $n++;
}
$out = array();
foreach ($var as $key => $value){
// $out[] = array_merge_recursive($value, $var2[$key]);
foreach ($var2 as $key => $value) {
$out1[] = array_merge_recursive($var[$key], $var2[$key]);
}
}
print_r(json_encode($out1));
However, this outputs
appleone
bananatwo
appleone
bananatwo
and I want to display it like this instead
appleone
appletwo
bananaone
bananatwo
Try this,
$var = array (1,2);
$var2 = array (a,b);
$out = array();
foreach ($var as $key => $value){
foreach($var2 as $k=>$v){
$out[] = $value.$v;
}
}
print_r(json_encode($out));
I think your loop should be something like this. There's no need of using array_merge_recursive function
$var = array (1,2);
$var2 = array ('a','b');
$result = array();
foreach($var as $key => $val){
foreach($var2 as $k => $v){
$result[] = $val.$v;
}
}
There is no need to use array_merge_recursive just a nested loop will suffice:
$var = array (1,2);
$var2 = array ('a','b');
$out = array();
foreach($var as $arrayNumeric){
foreach($var2 as $arrayAlphaNumeric){
$out[] = $arrayNumeric.$arrayAlphaNumeric;
}
}
as you can see in my code below, I'm using the same code (foreach loop with array assignment and trailing json_decode) three times for three variables that are structured similarly. I'm wondering how I can optimize my code so that it doesn't repeat functions unnecessarily. Would variable variables be helpful in this situation? Can I move the recurring lines of code to inside the first foreach statement?
Here's what my code looks like now:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB', 'ZNGA' => 'http://ichart.finance.yahoo.com/table.csv?s=ZNGA');
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
}
$MSFT = json_encode(array_reverse($MSFT));
foreach($AAPL_data as $val){
$AAPL[] = array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
}
$AAPL = json_encode(array_reverse($AAPL));
foreach($FB_data as $val){
$FB[] = array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
}
$FB = json_encode(array_reverse($FB));
Thanks. Let me know if you have any questions.
For the three loops, try:
function dateCloseLoop($data) {
foreach($data as $val){
$tmp[] = array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
}
return json_encode(array_reverse($tmp));
}
So your code would be something like:
$MSFT = dateCloseLoop($MSFT_data);
$AAPL = dateCloseLoop($AAPL_data);
$FB = dateCloseLoop($FB_data);
You could just use an associative array, storing a data array for each stock key, and use nested foreach's on that nested array.
Something like this:
$res = array();
$stocks = array('MSFT' => '...', 'AAPL' => '...', 'FB' => '...', 'ZNGA' => '...');
foreach ($stocks as $stock => $url) {
$fh = fopen($url, 'r');
$header = fgetcsv($fh);
$res[$stock] = array();
while ($line = fgetcsv($fh)) {
$res[$stock][] = array_combine($header, $line);
}
fclose($fh);
}
$json = array();
foreach ($res as $stock => $data) {
$out = array();
foreach($data as $val){
$out[] = array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
}
$json[$stock] = json_encode(array_reverse($out));
}
There is some problem, the code below assigning the last pr_name to all keys.
$arr = array();
while($row = mysql_fetch_array($results)) {
$keys[] = $row['pr_code'];
$items = array_fill_keys($keys, $row['pr_name']);
}
Simply with this:
$items = array();
while($row = mysql_fetch_array($results)) {
$items[$row['pr_code']] = $row['pr_name'];
}
If I want to add values to an array in a while loop I could do $arr[] = "some". But how can I do this if I have an associative array, for example:
while($result = $result->fetch_array(MYSQLI_ASSOC))
{
$arr[]["some_key"] = "some";
$arr[]["other_key"] = "some2";
}
But this will give me something like Array ( [0] => Array ( [some_key] => some) [1] => Array ( [other_key] => some2). So what is the right way to add values into an associative array inside a loop?
Create a temporary array for your keys, and then push that temporary array onto the main one:
$arr = [];
loop(condition) {
$tmp = [];
$tmp['some_key'] = 'some value';
$tmp['other_key'] = 'other value';
$arr[] = $tmp;
}
This will not overwrite your values:
$arr = array();
while($result = $result->fetch_array(MYSQLI_ASSOC))
{
$tmp = array();
foreach($result as $key=>$value)
{
$tmp[$key] = $value;
}
$arr[]=$tmp;
}
Or more succinctly:
$arr = array();
while($result = $result->fetch_array(MYSQLI_ASSOC))
{
$arr[]=$result;
}
Since PHP defaults to copying rather than referencing.
If you wanted to store them as an assoc. array of arrays you might do this:
$arr = array();
while($result = $result->fetch_array(MYSQLI_ASSOC))
{
foreach($result as $key=>$value)
{
if(!isset($arr[$key])){
$arr[$key] = array();
}
$arr[$key][] = $value;
}
}