I have an array.
my array:
while($rowop = mysql_fetch_array($resultop))
{
$info[] = array(
'status'=>$rowop[2],
'day' => $rowop[3],
'from'=>$rowop[4],
'to' => $rowop[5],
'mon'=>$rowop[6],
'tue' => $rowop[7],
'wed'=>$rowop[8],
'thu' => $rowop[9],
'fri'=>$rowop[10],
'sat' => $rowop[11],
'sun'=>$rowop[12]
);
}
value of $rowop[6],$rowop[7],$rowop[8],$rowop[9],$rowop[10],$rowop[11],$rowop[12] can be 'on' or 'off'. I want to show only those rows which contain 'off' value. array will be same as:
'status'=>'ok',
'day' =>'all',
'from'=>'12pm',
'to' => '8am',
'off day'=>'tue,wed,thu,sat,sun'
Any one please give me Idea.if possible give example
Try this, ( assuming your array name is $info ) :
$result = array();
foreach($info as $key=>$value){
$result[$key]['status'] = $value['status'];
$result[$key]['day'] = $value['day'];
$result[$key]['from'] = $value['from'];
$result[$key]['to'] = $value['to'];
$off=array();
foreach ($value as $k => $v) {
if($v=="off") $off[]=$k;
}
if($off) $off_days = implode (", ", $off);
$result[$key]["off day"] = $off_days;
}
print_r($result);
What about this?
$days = ['mon','tue','wed','thu','fri','sat','sun'];
for($offs=[],$i=6,$i<=12,$i++) if($rowtop[$i]=='off') $offs[]= $days[$i-6];
$info[] = array(
'status'=>$rowop[2],
'day' => $rowop[3],
'from'=>$rowop[4],
'to' => $rowop[5],
'off day' => implode(',', $offs)
);
How about following code
I didn't test it. Fix if there are any errors
$days = array('mon','tue', 'wed', 'thu', 'fri', 'sat', 'sun');
$selected = array();
$final = array();
foreach($days as $day)
{
if(isset($info[$day]))
if($info[$day] == 'off')
$selected[] = $info[$day];
}
$all_days = implode(',', $selected);
$final['status'] = $info['status'];
$final['day'] = $info['day'];
$final['from'] = $info['from'];
$final['to'] = $info['to'];
$final['off day'] = $all_days;
This can be achieved in multiple steps:
Find all keys with off status using array_filter() and store it in array $result
Remove all the "week keys", i.e. mon, tue, wed etc. using array_diff_key()
Implode $result array to get a comma-separated string, and use that to create a new array element
Code:
// find all keys with 'off' status
$status = 'off';
$result = array_keys(array_filter($info,
function($element) use ($status) {
return $element == $status;
}
));
// remove all week keys
$keys = array('mon','tue','wed','thu','fri','sat','sun');
$info = array_diff_key($info, array_flip($keys));
// create a new array item with the comma-separated key string
$info['off_days'] = implode(',', $result);
print_r($info);
Output:
Array
(
[status] => ok
[day] => all
[from] => 12pm
[to] => 8am
[off_days] => tue,wed,thu,sat,sun
)
Demo.
An example using array_filter
$days = array('mon','tue', 'wed', 'thu', 'fri', 'sat', 'sun');
while($rowp ....) { //
$offs = implode (
',',
array_keys(
array_filter(
array_intersect_key($oneRow, array_flip($days)),
function($i) {return $i == 'off'}
)
)
);
//...
}
where $oneRow is what you are filling the $info array with.
Hope it helps
Related
I have two array containing some value.
$type = array("first", "second", "third");
$date = array(
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
);
I need output something like this:
[
type :first,
date: [
"2019-04-30": 1.2,
.....
]
]
But for some reason I am not getting in that format.
This is the code I have tried.
$newArr = array();
foreach($type as $tt) {
$newArr[]['type'] = $tt;
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[]['date'] = $newDate;
}
Can anybody show what I did mistake.
Thank You.
It just comes down to building the array and then adding it in the right order, this builds all of the data and adds it in one go at the end of the loop...
$newArr = array();
foreach($type as $tt) {
$newDate = array();
foreach ($date as $d) {
$newDate[$d] = 1.2;
}
$newArr[] = [ 'type' => $tt, 'date' => $newDate];
}
You could shorten it to this, but it doesn't really make much difference...
foreach($type as $tt) {
$newArr[] = [ 'type' => $tt, 'date' => array_fill_keys($date, 1.2)];
}
Lets make it more simple
$newArr = array();
$newdates = array();
foreach($dates as $date){
$newdates[$date] = 1.2;
}
foreach($type as $tt) {
$newArry[] = array("type"=>$tt,"date"=>$newdates);
}
You can use array_map and array_fill_keys for the desired result
$type = ["first", "second", "third"];
$date = [
0 => "2019-04-30",
1 => "2019-05-01",
2 => "2019-05-02",
3 => "2019-05-03"
];
$newArr = [];
array_map(function($t, $d) use ($date, &$newArr){
$newArr[] = [
'type' => $t,
'date' => array_fill_keys($date, 1.2)
];
}, $type, $date);
I have an array in PHP:-
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"]
Here I want to group together elements based on same ending integer together in json like
$post_data = array(
'0' => array(
'BX_NAME0' => $item_type,
'BX_categoryName0' => $string_key,
'BHA_categories0' => $string_value
),
'1' => array(
'BX_NAME1' => $item_type,
'BX_categoryName1' => $string_key,
'BHA_categories1' => $string_value
),
);
I have Used:- filter_var($key , FILTER_SANITIZE_NUMBER_INT);
to get the integer part of the array elements but don't known how to group them further.
You can do it like below using preg_match():-
$new_array = array();
foreach ($arr as $ar){
preg_match_all('!\d+!', $ar, $matches); //get the number from string
$new_array[$matches[0][0]][$ar] = '';
}
echo "<pre/>";print_r($new_array);
Output:- https://eval.in/715548
It should be something like this:-
$arr = array("BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2");
$post_data = array();
foreach($arr as $value) {
$key = filter_var($value , FILTER_SANITIZE_NUMBER_INT);
if(isset($post_data[$key]) && !is_array($post_data[$key])) {
$post_data[$key] = array();
}
$post_data[$key][] = $value;
}
print_r($post_data);
Tested and works
However, I suggest you use substr() to get the last character of the array item, for performance and stuff..
By using filter_var() method
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"];
foreach($arr as $a){
$int = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$newarr[$int][$a] = '';
}
print_r($newarr);
Output:-https://eval.in/715581
I have this array
$date = array{"2013-09-17 00:21:00",
"2013-09-23 00:12:00",
"2013-09-23 00:41:00",
"2013-09-20 00:13:00",
"2013-09-19 00:34:00",
"2013-09-17 00:38:00"}
I'm trying to sum the time inside the array that have the same date.
This is my expected output:
$date = array{"2013-09-17 00:59:00",
"2013-09-23 00:53:00",
"2013-09-20 00:13:00",
"2013-09-19 00:34:00"}
Now this is what I have tried so far
foreach($date as $key => $value)
{
$lf_date[] = date("Y-m-d",strtotime($value));
$lf_time[] = date("H:i:s",strtotime($value));
if(isset($lf_date[$key]))
{
$output[] += $lf_time[$key];
}
else
{
$output[] = $lf_time[$key];
}
}
This gives me a 0 output T_T.. I already tried searching on google and it says that I have to use isset and array_key_exists but I can't get it to work. :(. Thanks for anyone who could help me.
Use:
<?php
$date = array("2013-09-17 00:21:00",
"2013-09-23 00:12:00",
"2013-09-23 00:41:00",
"2013-09-20 00:13:00",
"2013-09-19 00:34:00",
"2013-09-17 00:38:00");
$array = array();
foreach($date as $key => $value)
{
$lf_date = date("Y-m-d",strtotime($value));
$lf_time = date("H:i:s",strtotime($value));
$midnight = strtotime("0:00");
if(!isset($array[$lf_date]))
$array[$lf_date] = 0;//check is array index exists
$array[$lf_date] += strtotime($lf_time) - $midnight;
}
foreach($array as $key => $value)
{
$midnight = strtotime("0:00");
$array[$key] = $key." ".date("G:i:s", $midnight + $value);
}
$result = array_values($array);
print_r($result);
?>
Output:
Array
(
[0] => 2013-09-17 0:59:00
[1] => 2013-09-23 0:53:00
[2] => 2013-09-20 0:13:00
[3] => 2013-09-19 0:34:00
)
For a rent application, I have an array $dates like this:
Array
(
[2013-07-19] => 1
[2013-07-21] => 3
[2013-07-23] => 2
[2013-07-24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => 2
[2013-07-30] => 3
[2013-07-31] => 1
)
The date is the key, and the values are the number of items rent in that day for a specific product
How can I split this array in many sub arrays containing each a list of consecutive days?
Like this:
Array
(
[0] => Array
(
[2013-07-19] => 1
)
[1] => Array
(
[2013-07-21] => 3
)
[2] => Array
(
[2013-07-23] => 2
[2013-07-24] => 4
[2013-07-25] => 4
[2013-07-26] => 2
[2013-07-27] => 2
)
[3] => Array
(
[2013-07-30] => 3
[2013-07-31] => 1
)
)
$newArray = array();
foreach ($array as $date => $value)
{
// Make sure the newArray starts off with at least one element
if (empty($newArray))
$newArray[] = array();
// Calculate the difference in dates.
// (I like using DateTime, but use whichever method you like)
$dateTime = new DateTime($date);
$lastDateTime = new DateTime($lastDate);
$dateDiff = $dateTime->diff($lastDateTime);
// Add a new array to the end if the difference between this element and the last was more than a day
if ($dateDiff->days > 1)
$newArray[] = array();
// We can now be guaranteed that the last element of $newArray is the one we want to append to
$newArray[count($newArray) - 1][$date] = $value;
// Keep track of the last date you saw
$lastDate = $date;
}
Here it is in action: https://eval.in/38039
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = end(explode('-', next($array[$date])));
if ($thisDay + 1 != $nextDay + 0)
$i++;
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
}//END FOREACH LOOP
This is the code i would use to do what you are asking.
UPDATE:
I was wrong above. i have altered the code to work this time:
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = array_key_exists(date('Y-m-d', strtotime($date . ' +1 day')), $array);
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
if (!$nextDay)
$i++;
}//END FOREACH LOOP
Here is my test case:
<?php
$array = array(
'2013-07-19' => 1,
'2013-07-21' => 3,
'2013-07-23' => 2,
'2013-07-24' => 4,
'2013-07-25' => 4,
'2013-07-26' => 2,
'2013-07-27' => 2,
'2013-07-30' => 3,
'2013-07-31' => 1
);
echo '<pre>' . print_r($array, true) . '</pre>';
$newArray = array();
$i = 0;
foreach ($array as $date => $key) {
$thisDay = end(explode('-', $date));
$nextDay = array_key_exists(date('Y-m-d', strtotime($date . ' +1 day')), $array);
if (!isset($newArray[$i])) {
$newArray[$i] = array($date => $key);
} else {
if (!isset($newArray[$i][$date])) {
$newArray[$i][$date] = $key;
} else {
$newArray[$i][$date] = $key;
}//END IF
}//END IF
if (!$nextDay)
$i++;
}//END FOREACH LOOP
echo '<pre>' . print_r($newArray, true) . '</pre>';
?>
you can do it like this:
$data = array(
'2013-07-19' => 1,
'2013-07-21' => 3,
'2013-07-23' => 2,
'2013-07-24' => 4,
'2013-07-25' => 4,
'2013-07-26' => 2,
'2013-07-27' => 2,
'2013-07-30' => 3,
'2013-07-31' => 1
);
$result = array();
$ref = new DateTime('1821-11-11');
foreach ($data as $datum => $nb) {
if ($ref->add(new DateInterval('P1D'))->format('Y-m-d')!=$datum) {
$result[] = array();
$ref = new DateTime($datum);
}
$result[array_pop(array_keys($result))][$datum] = $nb;
}
print_r($result);
Consider following array
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n')
);
Here I would like to sort with head and membkey. Top element of same membkey element should have 'head=y' and echoed as,
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n')
);
I tried it as follows
function orderbymemberKey( $a, $b ){
if ( $a[membkey] == $b[membkey] )
return 0;
return($a[membkey] < $b[membkey] )? -1 :1;
}
usort( $details, orderbymemberKey );
and it successfully order by membkey.
Any suggestions please.
You're half way there (though you were sorting backwards for membkey based on your example):
function order_by_member_key($a, $b)
{
if ($a['membkey'] == $b['membkey'])
{
// membkey is the same, sort by head
if ($a['head'] == $b['head']) return 0;
return $a['head'] == 'y' ? -1 : 1;
}
// sort the higher membkey first:
return $a['membkey'] < $b['membkey'] ? 1 : -1;
}
usort($details, "order_by_member_key");
Is this array being pulled from a database? Because, if so, you should be able to make use of ORDER BY clauses to clean it up outside of php.
<?php
$membkey = array();
$head = array();
foreach ($details as $key => $row) {
$membkey[$key] = $row['membkey'];
$head[$key] = $row['head'];
}
array_multisort($membkey, SORT_DESC, $head, SORT_DESC, $details);
print_r($details);
Or, an even more generic solution:
function sort_by($array) {
$arguments = func_get_args();
$array = array_pop($arguments);
$variables = array();
foreach ($arguments as $index => $key) {
$variables[] = '$arguments['.$index.']';
if ($index % 2 == 0) {
$arguments[$index] = array();
foreach ($array as $row) $arguments[$index][] = $row[$key];
}
}
// call_user_func_array will not work in this case
eval('array_multisort('.implode(', ', $variables).', $array);');
return $array;
}
print_r(sort_by('membkey', SORT_DESC, 'head', SORT_DESC, $details));
Ugly but someone wrote a function on php.net:
http://php.net/manual/en/function.sort.php
<?php
$array[0]['name'] = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year'] = '1978';
$array[0]['address'] = 'Street 1';
$array[1]['name'] = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year'] = '1990';
$array[1]['address'] = 'Street 2';
$array[2]['name'] = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year'] = '1982';
$array[2]['address'] = 'Street 3';
function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
// sort by ?
foreach ($array as $pos => $val)
$tmp_array[$pos] = $val[$sort_by];
asort($tmp_array);
// display however you want
foreach ($tmp_array as $pos => $val){
$return_array[$pos][$sort_by] = $array[$pos][$sort_by];
$return_array[$pos][$key1] = $array[$pos][$key1];
if (isset($key2)){
$return_array[$pos][$key2] = $array[$pos][$key2];
}
if (isset($key3)){
$return_array[$pos][$key3] = $array[$pos][$key3];
}
if (isset($key4)){
$return_array[$pos][$key4] = $array[$pos][$key4];
}
if (isset($key5)){
$return_array[$pos][$key5] = $array[$pos][$key5];
}
if (isset($key6)){
$return_array[$pos][$key6] = $array[$pos][$key6];
}
}
return $return_array;
}
//usage (only enter the keys you want sorted):
$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);
//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )