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;
}
}
Related
I want to group in subarray the identical values while preserving the original order of each group of values.
I want this :
array('a','b','b','c','c','c','a','a');
to become :
array( array('a'),array('b','b'),array('c','c','c'),array('a','a'));
$source = array('a','b','b','c','c','c','a','a');
$tempvalue = false;
$temparr = array();
$new = array();
foreach ($source as $value) {
if ($tempvalue && $value != $tempvalue){
$new[] = $temparr;
$temparr = array();
}
$temparr[] = $value;
$tempvalue = $value;
}
$new[] = $temparr;
echo json_encode($new);
output:
[["a"],["b","b"],["c","c","c"],["a","a"]]
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 want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on
$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.
There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}
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;
}
}
I have the following key/value from my $_POST variable:
Array
(
'translations_0_comment' => 'Greetings from UK'
)
What I would like is to set this values to the following array
$data[translations][0][comment] = 'Greetings from UK';
So the idea is that I can have anything in my KEY values, and from that I will populate an array.
Is there any safe way to do this without using eval() ?
All help is appreciated.
UPDATE:
this would be the idea with eval()
foreach ($_POST as $key => $dataValue) {
$a = explode("_", $key);
$builder = '$object';
foreach ($a as $value) {
$builder.='['.$value.']';
}
$builder.=' = '.$dataValue.';';
eval($builder);
}
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
explode() is what you need:
$data = array();
foreach ($postData as $key => $val) {
$explodedKey = explode('_', $key);
$data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}
No need to use eval().
I think this is what you are looking for
Example
In your form which generate the $_POST data rename the input attribute as follows
<input name="data[translations][0][comment]" />
and now your $_POST['data'] will be an array
$data = array();
foreach ($_POST as $keys => $val) {
$keys_list = explode('_', $keys);
$link = &$data;
foreach ($keys_list as $key) {
$link[$key] = $val;
$link = &$link[$key];
}
}
Try this one sir.
$array = array
(
'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);
$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);
$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
$start .= "array(\"".$array1[$i]."\" => ";
$end .=")";
}
$start = $start ."\"".$arrValue[0]."\"".$end;
eval("\$arr = $start;");
print_r($arr);