I have an array and the createtime is already sorted by AES.
$list = array(0 => array('createtime' => 90,'message'=>'ad','user'=>'a'),
1 => array('createtime' => 91,'message'=>'ae','user'=>'b'),
2 => array('createtime' => 93,'message'=>'ae','user'=>'b'),
3 => array('createtime' => 93,'message'=>'ae','user'=>'c'),
4 => array('createtime' => 94,'message'=>'ah','user'=>'d'),
5 => array('createtime' => 99,'message'=>'ah','user'=>'a'),
6 => array('createtime' => 100,'message'=>'ah','user'=>'a'));
As you can see,maybe the array is from a sql table,what I want is to deal with these data,the result of array like this.
$list = array(0 => array('createtime' => 90,'message'=>'ad','user'=>'a'),
1 => array('createtime' => 91,'message'=>'ae+ae','user'=>'b'),
2 => array('createtime' => 93,'message'=>'ae','user'=>'c'),
3 => array('createtime' => 94,'message'=>'ah','user'=>'d'),
4 => array('createtime' => 99,'message'=>'ah+ah','user'=>'a'));
Yeah, you may find the createtime between 5 and the same user data combined.What I want is just like this,and in the future it may includes more users and more createtimes.
And I coded like this to deal with it,but it worked not well when I change my datas like add user or change user and so on.
$diff = 0;
$count = 0;
$d = array();
$j = array();
for($i = 1;isset($list[$i]);){
if ($list[$i]['user'] != $list[$i-1-$count]['user']) {
if (!in_array($list[$i]['user'], $d)) {
$d[$diff] = $list[$i]['user'];
$j[$diff] = $i;
$count++;
$diff++;
$i++;
continue;
} else {
$i++;
$count++;
continue;
}
}
if($list[$i]['createtime'] - $list[$i-1-$count]['createtime'] < 5){
$list[$i-1-$count]['message'] = $list[$i-1-$count]['message'].'<br>'.$list[$i]['message'];
array_splice($list,$i,1);
} else if ($count == 0) {
$i++;
} else {
$i = $j[0] + 1;
$count = 0;
$diff = 0;
$d = array();
$j = array();
}
}
It seems to have something wrong.So how should I do to meet my requirements.And more users between short createtime should also be considered.Thanks.
So, you're after something like this?
$list = array(0 => array('createtime' => 90,'message'=>'ad','user'=>'a'),
1 => array('createtime' => 91,'message'=>'ae','user'=>'b'),
2 => array('createtime' => 93,'message'=>'ae','user'=>'b'),
3 => array('createtime' => 93,'message'=>'ae','user'=>'c'),
4 => array('createtime' => 94,'message'=>'ah','user'=>'d'),
5 => array('createtime' => 99,'message'=>'ah','user'=>'a'),
6 => array('createtime' => 100,'message'=>'ah','user'=>'a'));
$out = array();
$prevUser = 0;
foreach($list as $key => $value){
if($value['user'] === $prevUser){
echo $value['user'], $prevUser, '<br>';
end($out);
$k = key($out);
$out[$k]['message'] .= $value['message'];
continue;
}
$out[] = $value;
$prevUser = $value['user'];
}
echo '<pre>';
print_r($out);
Related
I have the following array:
Array ( [10] => 06:30pm [20] => 04:00pm [30] => 05:15pm )
The number in [] is the id and follow by the value is time. I need to sort this array by time while maintaining the id like this
Array ( [20] => 04:00pm [30] => 05:15pm [10] => 06:30pm )
Please also note that the time can be in AM or PM also.
I would then need to extract the id in the [] as comma separated value.
Can anyone help?
try this
<?php
$time= ['10' => '06:30pm','20' => '04:00pm', '30' => '05:15am'];
$temp_time=array();
foreach ($time as $key => $value) {
if(sizeof(explode("pm", $value))>1){
$data=explode(":", $value);
$data[0]=(int)$data[0]+12;
$value=$data[0].':'.$data[1];
}else{
$data=explode(":", $value);
if($data[0]=='12'){
$value='00:'.$data[1];
}else{
$value=$data[0].':'.$data[1];
}
}
$temp_time+=[$key => $value];
}
asort($temp_time);
$new_time=array();
foreach ($temp_time as $key => $value) {
$new_time+=[$key => $time[$key]];
}
print_r($new_time);
output:
Array ( [30] => 05:15am [20] => 04:00pm [10] => 06:30pm )
Here is the solution:
$source_array = array(10 => '06:30pm', 20 => '04:00pm', 30 => '05:15pm', 40 => '04:00am');
function arr_swap_elements(&$arr, $a_index, $b_index) {
$tmp = $arr[$a_index];
$arr[$a_index] = $arr[$b_index];
$arr[$b_index] = $tmp;
return;
}
function arr_sort_by_time(&$source_array, $start_index = 0, $arr_keys = null, $arr_len = null) {
if (is_null($arr_keys)) {
$arr_keys = array_keys($source_array);
}
if (is_null($arr_len)) {
$arr_len = count($source_array);
}
for ($i = $start_index; $i < $arr_len; $i++) {
if ($i > 0) {
if (strtotime($source_array[$arr_keys[$i]]) > strtotime($source_array[$arr_keys[$i - 1]])) {
$was_swapped = true;
arr_swap_elements($source_array, $arr_keys[$i], $arr_keys[$i - 1]);
}
}
}
if ($start_index + 1 < $arr_len) {
arr_sort_by_time($source_array, $start_index + 1, $arr_keys, $arr_len);
}
}
arr_sort_by_time($source_array);
var_dump($source_array);
I need to nest 3 arrays (so the first array contains an array, which also contains an array). Im having success with 2 arrays but I can't get 3 to work.
I had my code working with 2 arrays (which worked jusr fine) but I can't get 3 arrays to be nested.
My current code:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
/*$row_array["sectionIndicators"][] = array(
"iid" => intval($v["iid"]),
"iname" => $v["iname"],
"perc" => intval($v["perc"]),
"pvalue" => intval($v["pvalue"]),
"vfixed" => intval($v["vfixed"])
);*/
$row_array["sectionIndicators"]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"]["iname"] = $v["iname"];
$row_array["sectionIndicators"]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"]["finalArray"] = array();
}
}
}
array_push($data, $row_array);
}
}
The part that I commented out is my working part (with 2 arrays).The new part works but only contains the last row of $indicators so it seems like the loop isn't working this way.
The $row_array["sectionIndicators"]["finalArray"] = array(); will contain the last nested array.
Any help is much appreciated.
SOLUTION
I found out that I had to give an index. My solution:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
$i=-1;
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
$i++;
$row_array["sectionIndicators"][$i]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"][$i]["iname"] = $v["iname"];
$row_array["sectionIndicators"][$i]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"][$i]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"][$i]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"][$i]["finalArray"] = array();
array_push($row_array["sectionIndicators"][$i]["finalArray"],
intval($v["perc"]),
intval($d["id"]),
intval($v["iid"])
);
}
}
}
array_push($data, $row_array);
}
}
<?php
// Assumption that your array is like this :
$sections = [0 => ['id'=>1, 'sname'=>'Sname', 'sicon'=>'SIcon', 'perc'=>'Perc', 'pvalue'=>'Pvalue', 'vfixed'=>'Vfixed'], 1 => ['id'=>2, 'sname'=>'Sname2', 'sicon'=>'SIcon2', 'perc'=>'Perc2', 'pvalue'=>'Pvalue2', 'vfixed'=>'Vfixed2']];
$indicators = [ 0 => ['idsec'=>1, 'iid'=>1, 'iname'=>'viname', 'perc'=>'vperc', 'pvalue'=>'vpvalue', 'vfixed'=>'vVfixed'], 1 => ['idsec'=>2, 'iid'=>2, 'iname'=>'viname2', 'perc'=>'vperc2', 'pvalue'=>'vpvalue2', 'vfixed'=>'vVfixed2']];
// Initialisation your result array
$data = [];
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
//loop indicators
if (!empty($indicators)) {
foreach ($indicators as $v) {
if ($d['id'] == $v['idsec']) {
$row_array["sectionIndicators"] = array();
$row_array["sectionIndicators"][] = array(
"iid" => intval($v["iid"]),
"iname" => $v["iname"],
"perc" => intval($v["perc"]),
"pvalue" => intval($v["pvalue"]),
"vfixed" => intval($v["vfixed"])
);
$row_array["sectionIndicators"]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"]["iname"] = $v["iname"];
$row_array["sectionIndicators"]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"]["finalArray"] = array();
}
}
}
array_push($data, $row_array);
}
}
echo '<pre>';
print_r( $data );
Result :
Array
(
[0] => Array
(
[id] => 1
[sname] => Sname
[sicon] => SIcon
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[sectionValues] => Array
(
[0] => 0
[1] => 1
[2] => 0
)
[sectionIndicators] => Array
(
[0] => Array
(
[iid] => 1
[iname] => viname
[perc] => 0
[pvalue] => 0
[vfixed] => 0
)
[iid] => 1
[iname] => viname
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[finalArray] => Array
(
)
)
)
[1] => Array
(
[id] => 2
[sname] => Sname2
[sicon] => SIcon2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[sectionValues] => Array
(
[0] => 0
[1] => 2
[2] => 0
)
[sectionIndicators] => Array
(
[0] => Array
(
[iid] => 2
[iname] => viname2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
)
[iid] => 2
[iname] => viname2
[perc] => 0
[pvalue] => 0
[vfixed] => 0
[finalArray] => Array
(
)
)
)
)
I found out that I had to give an index. My solution:
if (!empty($sections)) {
foreach ($sections as $d) {
$row_array = array();
$row_array["id"] = intval($d["id"]);
$row_array["sname"] = $d["sname"];
$row_array["sicon"] = $d["sicon"];
$row_array["perc"] = intval($d["perc"]);
$row_array["pvalue"] = intval($d["pvalue"]);
$row_array["vfixed"] = intval($d["vfixed"]);
$row_array["sectionValues"] = array();
array_push($row_array["sectionValues"],
intval($d["perc"]),
intval($d["id"]),
0
);
$row_array["sectionIndicators"] = array();
//loop indicators
if (!empty($indicators)) {
$i=-1;
foreach ($indicators as $v) {
if ($d["id"] == $v["idsec"]) {
$i++;
$row_array["sectionIndicators"][$i]["iid"] = intval($v["iid"]);
$row_array["sectionIndicators"][$i]["iname"] = $v["iname"];
$row_array["sectionIndicators"][$i]["perc"] = intval($v["perc"]);
$row_array["sectionIndicators"][$i]["pvalue"] = intval($v["pvalue"]);
$row_array["sectionIndicators"][$i]["vfixed"] = intval($v["vfixed"]);
$row_array["sectionIndicators"][$i]["finalArray"] = array();
array_push($row_array["sectionIndicators"][$i]["finalArray"],
intval($v["perc"]),
intval($d["id"]),
intval($v["iid"])
);
}
}
}
array_push($data, $row_array);
}
}
I would like to accumulate values in an associative array depending on part of the key.
I have tested this foreach loop which works fine in an indexed array:
$b = array();
foreach ($a as $key => $value) {
if ($key > 0) {
$b[$key] = $b[$key - 1] + $value;
}
}
I can't get it to work in an associative array, though...
$a (excerpt)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 0
[2014-06-03|Paul] => 1
[2014-06-12|Paul] => 0
[2014-08-11|Paul] => 1
[2014-08-28|Paul] => 3
[2012-05-09|John] => 1
[2012-08-29|John] => 2
[2012-09-05|John] => 0
[2012-09-13|John] => 1
)
$b (desired result)
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
In the desired result each value is of 'Paul' and 'John' (and more) is accumulated to the previous one.
You can do this by keeping track of the name parts of the keys, and resetting the total count when you get to a new name:
$b = array();
$lastname = '';
foreach ($a as $key => $value) {
list($d, $n) = explode('|', $key);
if ($n == $lastname) {
$total += $value;
}
else {
$total = $value;
}
$b[$key] = $total;
$lastname = $n;
}
print_r($b);
Output:
Array (
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
Demo on 3v4l.org
By using array_walk, check if current name is same as next name, as per that I am resetting value by next.
$result = [];
$tempKey = '';
$arr = array_walk($arr, function($item, $key) use(&$result, &$tempKey, &$total){
list($date, $name) = explode("|", $key); // explode key
if(empty($tempKey) || $tempKey != $name){ // if empty or if conflict
$tempKey = $name; // tempKey for reference
$total = $item; // total reset to current value
}else{
$total += $item; // adding for same name
}
$result[$key] = $total; // putting calculated value
});
print_r($result);
Output
Array
(
[2014-04-22|Paul] => 0
[2014-04-28|Paul] => 2
[2014-05-13|Paul] => 2
[2014-06-03|Paul] => 3
[2014-06-12|Paul] => 3
[2014-08-11|Paul] => 4
[2014-08-28|Paul] => 7
[2012-05-09|John] => 1
[2012-08-29|John] => 3
[2012-09-05|John] => 3
[2012-09-13|John] => 4
)
Demo.
$data1 = array();
$final_ttt = "15";
$items = [];
for ($j = 1; $j <= $final_ttt; ++$j)
{
$TeamNo = "t$j";
$items[] = $TeamNo;
}
print_r($items);
In while loop im getting below values
$day = 1;
$i = 0;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
$data1[]=array("name" => $name,"loopvalue" => $loopvalue);
if( $i % $final_ttt == 0 )
{
$fday = "Day ".$day;
$day++;
}
}
output
name value Team day
a 2 t1,t12 1
b 3 t3,t4,t5 1
c 8 t5,t6,t7,t8,t9,t10,t11,t12 1
d 3 t13,t14,t15 1
e 4 t1,t2,t3,t4 2
How to allocate the teams to based on while loop value. if i get value is 2 => then i need to allocate first 2 teams t1,t2 like this. kinldy help me.
Thanks you in advance
--- We are editing the question as the solution provided does not work in certain test cases. Like the one shown in the attached image.
Here is the updated code for above image output
$lastIndex = 0;
$day = 1;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
if($i==0)
{
$fday = "Day ".$day;//Day 1 for first Itration
$day = 2;
}
$team = implode(',',array_slice($items, $lastIndex, $loopvalue));
$lastIndex = $lastIndex + $loopvalue;
if($lastIndex > count($items))
{
$lastIndex = $lastIndex - count($items);
$team .= ','.implode(',',array_slice($items, 0, $lastIndex));
$fday = "Day ".$day;
$day++;
}
$data1[]=array("name" => $name,"loopvalue" => $loopvalue, "day" => $fday, 'team' => $team);
$row ++;
}
print_r($data1);
You can try something like below
$lastIndex = 0;
while($row = $qry->fetch())
{
$name = $row['name']; //a,b,c,d
$loopvalue = $row['loopvalue']; // getting 2,3,8,3,4
$team = implode(',',array_slice($items, $lastIndex, $loopvalue));
$lastIndex = $lastIndex + $loopvalue;
if($lastIndex > count($items)) {
$lastIndex = $lastIndex - count($items);
$team .= ','.implode(',',array_slice($items, 0, $lastIndex));
}
$data1[]=array("name" => $name,"loopvalue" => $loopvalue, 'team' => $team);
$row ++;
}
print_r($data1);
Will result like
Array ( [0] => Array ( [name] => a [loopvalue] => 2 [team] => t1,t2 ) [1] => Array ( [name] => b [loopvalue] => 3 [team] => t3,t4,t5 ) [2] => Array ( [name] => c [loopvalue] => 8 [team] => t6,t7,t8,t9,t10,t11,t12,t13 ) [3] => Array ( [name] => d [loopvalue] => 3 [team] => t14,t15,t1 ) [4] => Array ( [name] => e [loopvalue] => 4 [team] => t2,t3,t4,t5 ) )
Let me know if this solve your problem.
I have the following problem:
$multidmimensional = array(
[0] => array(
[0] => 1,
[1] => 2,
[2] => 3
);
[1] => array(
[0] => 5,
[1] => 6,
[2] => 7
);
...
[2] => array(
[0] =>,4
[1] => 5,
);
);
I can have one or more (nested) arrays, and lets take as an example the first two of the above arrays:
I should permutate them in the following way:
15
16
17
25
26
27
36
37
38
If I had for example those three arrays, I should get a result like this:
154
164
174
155
165
175
254
264
274
255
265
275
364
374
384
365
375
385
I am having some problems to make an algorithm that would fix this problem. Can anyone help me?
Thanks in advance.
That's a nice brain teasing question. Here's what I came up with, see the running demo for testing and adjusting.
$multidimensional = array(
0 => array(
0 => 1,
1 => 2,
2 => 3,
),
1 => array(
0 => 5,
1 => 6,
2 => 7,
),
2 => array(
0 => 4,
1 => 5,
),
); // just your input
$permutations = array();
$count = count($multidimensional);
for ($i = 0; $i < $count; $i++) {
$temp = array_map("permute",array($permutations),array($multidimensional[$i]));
$permutations = $temp[0];
}
print_r($permutations); // OUTPUT
function permute($base,$add) {
$result = array();
if (count($base) > 0) {
foreach ($base AS $val1) {
if (count($add) > 0) {
foreach ($add AS $val2) {
$result[] = $val1.$val2;
}
}
else {
$result = $base;
}
}
}
else {
$result = $add;
}
return $result;
}
I can not test it right now but this should work: (may contain typos)
function permute($arrays){
if(count($arrays)<2) return $arrays[0];//TODO error on count == 0
$array1 = array_shift($arrays);
$array2 = array_shift($arrays);
$results = array();
foreach($array1 as $elementOfOne){
foreach($array2 as $elementOfTwo){
$results[] = $elemnetOfOne . $elementOfTwo;
}
}
array_unshift($arrays, $results);
return permute($arrays);
}
$data = array
(
'1' => array(5, 6, 7),
'2' => array(9, 25, 14)
);
for($i=0; $i<=count(array_keys($data)); $i++) {
for($j=1; $j<=2; $j++) {
$values[$i][] = $data[$j][$i];
}
}
for($i=0; $i<count($values); $i++) {
shuffle($values[$i]);
}
$newData = array();
for($i=0; $i<3; $i++) {
for($j=1; $j<=2; $j++) {
$newData[$j][] = array_pop($values[$i]);
}
}
print_r($newData);
Fiddle