I have 36 check boxes... I call them with this.
Labeled like this.
<input type='checkbox' value='1' name='ck[]'>
Called like this
$checks = $_POST['ck']
$vars = array(
'ck1' => 'Demo',
'ck2' => 'Demo2',
'ck3' => 'Demo3',
'ck4' => 'Demo4',
'ck5' => 'Demo5',
'ck6' => 'Demo6',
'ck7' => 'Demo7',
'ck8' => 'Demo8',
'ck9' => 'Demo9',
'ck10' => 'Demo10',
);
foreach($vars as $key=>$default) {
$checks[$key] = !empty($checks[$key]) ? $default : '';
}
How can I now make it where 2 new variables = specifics from that post.
For instance,
$CH1 = checks[1] - checks[6];
$ch2 = checks[6] - checks[10];
And then,
How can I make it where if there are numbers in $CH1 it will list and break.. like this
$checks[1] . '<br>' . $checks[2] and so on....
UPDATE***
$vars = array(
'1' => 'Desktop',
'2' => 'Laptop Only',
'3' => 'Laptop / Dock',
'4' => 'Laptop Case',
'5' => 'Desk Phone',
'6' => 'Monitor',
'7' => 'Printer Access',
'8' => 'Printer - Personal',
'9' => 'Email(phone)',
'10' => 'Office 365',
'11' => 'Sharepoint',
'12' => 'Fax Fwd',
'13' => 'Adobe DC',
'14' => 'Apacheta',
'15' => 'Brightree',
'16' => 'TeamDME',
'17' => 'DirectView',
'18' => 'RingCentral',
'19' => 'Faxage',
'20' => 'Google Docs',
'21' => 'Badge Access',
'22' => 'Title Plate',
'23' => 'Bis Cards',
'24' => 'Travel',
'25' => 'Exp Reports',
'26' => 'Order Pads',
'27' => 'Demo Trilogy',
'28' => 'Stickers',
'29' => 'APS',
'30' => 'CBSS',
'31' => 'Conexis',
'32' => 'Evenfy',
'33' => 'Inventory',
'34' => 'AMEX',
'35' => 'Fuel Card',
'36' => 'Vehicle'
);
foreach($vars as $key=>$default) {
$checks[$key] = !empty($checks[$key]) ? $default : '';
}
When I echo $checks, it just says array.. does not show any numbers names that were checked.
If you are trying to dinamically read the values, you can construct the key value with the name you already have:
$num_a = 1;
$num_b = 6;
$CH1 = checks['ck' . $num_a] - checks['ck' . $num_b];
You might want to use array_slice:
$CH1 = array_slice($checks, 0, 6);
Now $CH1 will be an array with the first 6 checks only. To get the next 10 (for instance):
$CH2 = array_slice($checks, 6, 10);
...etc.
Then you can loop through them just like you would do with another array:
foreach($CH1 as $chk) {
//
}
If you want to check if any of those is numeric, use is_numeric:
foreach($CH1 as $chk) {
if (is_numeric($chk)) echo $chk . "<br>";
}
You can also filter an array based on a condition. Let's say you want to eliminate the empty elements from the $checks array:
$filtered = array_filter($checks, function ($chk) { return !empty($chk); });
... and now output that filtered array with each entry on a separate line:
echo implode('<br>', $filtered);
Finally, you can use array_intersect_key to get out of your $vars array only those elements that have been checked, as follows:
$result = array_intersect_key($vars, array_flip($_POST['ck']));
So, if the user had selected checkboxes with value 1, 5 and 10, the $results array will look like this:
array (
1 => 'Desktop',
5 => 'Desk Phone',
20 => 'Google Docs',
)
See it on eval.in.
I hope these ideas will all be helpful and of use to you.
Related
(In between Christmas meals) I am again stuck with the loop through array and group by logic.
here is the array I am given
$aTest = Array
(
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period5',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-04,
'period' => 'period2',
'category' => 'Indoor room',
'score' => 2
),
Array
(
'date' => 2017-05-04,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period5',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period1',
'category' => 'Gym Class',
'score' => 1
),
Array
(
'date' => 2017-05-03,
'period' => 'period4',
'category' => 'Indoor room',
'score' => 1
)
);
This time I like group by category and sum the score group by period. Y-axis will be the category and X-axis will be the period. In the end I need this for a google chart
/*period, total indoor, total gym, 'total indoor', 'total gym'*/
array(
['Period1', 0,1,'0','1'],
['Period2', 3,0,'3','0'],
['Period3', 0, 0,'0','0'],
['Period4', 4,0,'4','0'],
['Period5', 1,1,'1','1']
)
I have this php code:
foreach ($aTest as $value) {
//echo $value['period'].' - '.$value['score'].'<br/>';
if (empty($output[$value]['period']))
$output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
if(empty($output[$value]['category']))
$output[$value['catgeory']] = ['Gym Class' => 0, 'Indoor room' =>0];
$output[$value['category']] += $value['score'];
}
ksort($output);
but this only totals the score by Category and not by period.
I think I need to loop through the periods as well, but how?
You have a wrong logic here.
if (empty($output[$value]['period']))
$output[$value]['period'] = ['Period1' => 0, 'Period2' => 0, 'Period3' =>0, 'Period4' => 0, 'Period5' => 0];
that $value is an array and you try to check $output[$value]
I saw that you don't have any line sum periods Value.
I have a solution for your data.
What is my code do??
Sum score of the period by the category
For each merge period and category score to an array using arraySort category to set position of these category scores values
$temp = [];
$output = [];
foreach($aTest as $value){
$period = $value['period'];
$category = $value['category'];
// Create default values
if (empty($temp[$period])){
$temp[$period] = [];
}
if(empty($temp[$period][$category])){
$temp[$period][$category] = 0;
}
//Sum score
$temp[$period][$category] += $value['score'];
}
//After Forech we have an array with ['period name' => ['category name' => score]];
//Sort values of the category change it if you want, you can add more option such as (item type for add '' to values)
$arraySort = [
"Indoor room", //total indoor,
"Gym Class", // total gym,
"Indoor room", //'total indoor',
"Gym Class" //'total gym'
];
foreach($temp as $period => $catsScore){
$periodItem = [$period];
foreach($arraySort as $cat){
$periodItem[] = $catsScore;
}
$output[] = $periodItem;
}
I want to make a multiple where query with AND and OR. Suppose my array is:
array (size=8)
0 => array (size=2)
'timeline.type' => string 'videos' (length=6)
'timeline.sourceId' => string '7' (length=1)
1 => array (size=2)
'timeline.type' => string 'loadshedding' (length=12)
'timeline.sourceId' => string '5' (length=1)
2 => array (size=2)
'timeline.type' => string 'news' (length=4)
'timeline.sourceId' => string '3' (length=1)
3 => array (size=2)
'timeline.type' => string 'news' (length=4)
'timeline.sourceId' => string '5' (length=1)
The above array could be dynamic. I want to make active record query like:
(timeline.type = 'videos' AND timeline.sourceId = 7) OR (timeline.type = 'loadshedding' AND timeline.sourceId = 5) OR (timeline.type = 'news' AND timeline.sourceId = 3) // and so on.
I tried :
$this->db->select('timeline.id as postid, timeline.*, sources.*, subscription.*')->from('timeline');
$this->db->join('sources', 'sources.type = timeline.type and timeline.sourceId = sources.id');
$this->db->join('subscription', 'subscription.type = timeline.type and timeline.sourceId = subscription.sourceId');
foreach($sources as $source){ //$sources is an array like given above
$this->db->or_where($source);
}
$this->db->order_by("timeline.id", "DESC");
$this->db->limit(15);
But when I echo $this->db->last_query(); to see the query. It returns SELECT * FROM timeline only. What might be the problem. Thank you.
Your Code Should be like
$sources = array (
0 => array (
'timeline.type' => 'videos',
'timeline.sourceId' => '7' ),
1 => array (
'timeline.type' => 'loadshedding',
'timeline.sourceId' => '5' ) ,
2 => array (
'timeline.type' => 'news',
'timeline.sourceId' => '3' ),
3 => array (
'timeline.type' => 'news',
'timeline.sourceId' => '5')
);
end($sources); // move the internal pointer to the end of the array
$lastkey = key($sources);
$pr = "";
foreach($sources as $key=>$source)
{
if($key != $lastkey)
{
$pr.="( `timeline.type` = '". $source["timeline.type"] ."' and `timeline.sourceId` = " . (int) $source["timeline.sourceId"] . ") OR ";
}
else
{
$pr.="( `timeline.type` = '". $source["timeline.type"] ."' and `timeline.sourceId` = " . (int) $source["timeline.sourceId"] . ")";
}
}
$this->db->select('timeline.id as postid, timeline.*, sources.*, subscription.*')->from('timeline');
$this->db->join('sources', 'sources.type = timeline.type and timeline.sourceId = sources.id');
$this->db->join('subscription', 'subscription.type = timeline.type and timeline.sourceId = subscription.sourceId');
$this->db->where($pr);
$this->db->order_by("timeline.id", "DESC");
$this->db->limit(15);
Hi I am new in PHP and I am trying to merge 2 arrays but I don't want to get duplicates.I have been stuck a week now.
I have first array:
$existed_product = array(array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"2", 'price'=>"12"),
array('name'=>"ying", 'code'=>"AB001", 'qty'=>"5", 'price'=>"8"));
And I want to merge the second array:
$new_product= array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"10", 'price'=>"12");
I want to merge them and when it found duplicate product, just replace it with a newer array(has qty=10). The result looks like this:
$final_array=array(array('name'=>"pano", 'code'=>"BR0001", 'qty'=>"10", 'price'=>"12"),
array('name'=>"ying", 'code'=>"AB001", 'qty'=>"5", 'price'=>"8"));
Please help me.Thank you
Assuming new product always is a single array, and code is the identifyer, something like this
$existed_product = array(
array(
'name' => 'pano',
'code' => 'BR0001',
'qty' => '2',
'price' => '12' ),
array(
'name' => 'ying',
'code' => 'AB001',
'qty' => '5',
'price' => '8'
)
);
echo '<pre>', print_r( $existed_product, true ), '</pre>';
$new_product = array(
'name' => 'pano',
'code' => 'BR0001',
'qty' => '10',
'price' => '12'
);
foreach ( $existed_product as $no => $product ) {
if ( $new_product['code'] == $product['code'] ) {
$existed_product[$no]['qty'] = $new_product['qty'];
$existed_product[$no]['price'] = $new_product['price'];
}
}
echo '<pre>', print_r( $existed_product, true ), '</pre>';
i want to show my chart in my admin panel using GD library using php ..
i get date from my database but when i use any library to show this result in line chart it did not work & it did not show any errors.i can not get what i did wrong?
can anyone help me?
<?php
include ("../setting.php");
include("../classes/phpgraphlib.php");
$result = mysql_query("SELECT DATE_FORMAT(log_date, '%Y-%m-%d') as Date,count(*) as Count FROM log
where operation_type='Add' and user_id='82' and faculty_code='0' group by log_date order by log_date") or die(mysql_error());
$MultiDimArray = array();
$data = array();
while( $row = mysql_fetch_array($result , MYSQL_BOTH) )
{
$MultiDimArray[] = array ( 'Date' => $row['Date'], 'Count' => $row['Count'] );
}
foreach($MultiDimArray as $value)
{
if ( !array_key_exists($value['Date'], $data) ) {
$data[$value['Date']] = $value['Count'];
}
else{ $data[$value['Date']] += (string)$value['Count'];}
}
$data = array_map('strval', $data);
$graph = new PHPGraphLib(400,300);
$graph->addData($data);
$graph->setTitle("Site Statistics");
$graph->setBars(false);
$graph->setLine(true);
$graph->setDataPoints(true);
$graph->setDataPointColor("maroon");
$graph->setDatadata(true);
$graph->setDataValueColor("maroon");
$graph->setGoalLine(.0025);
$graph->setGoalLineColor("red");
$graph->setXdataHorizontal(true);
$graph->createGraph();
?> `
the output of $data array is like that:
array'2013-05-13' => string '7' (length=1)'2013-05-15' => string '3' (length=1)'2013-05-16' => string '5' (length=1)'2013-05-18' => string '8' (length=1)'2013-05-19' => string '2' (length=1)'2013-05-21' => string '2' (length=1)'2013-05-22' => string '10' (length=2)'2013-05-23' => string '2' (length=1)'2013-05-25' => string '1' (length=1)'2013-05-26' => string '8' (length=1)'2013-05-27' => string '19' (length=2)'2013-05-28' => string '7' (length=1)'2013-05-29' => string '3' (length=1)'2013-06-02' => string '11' (length=2)'2013-06-03' => string '2' (length=1)'2013-06-04' => string '7' (length=1)'2013-06-05' => string '3' (length=1)'2013-06-06' => string '2' (length=1)'2013-06-09' => string '15' (length=2)'2013-06-10' => string '5' (length=1)'2013-06-11' => string '1' (length=1)'2013-06-12' => string '3' (length=1)'2013-06-15' => string '10' (length=2)'2013-06-16' => string '3' (length=1)'2013-06-19' => string '2' (length=1)
I'd suggest using JS for that, feeding it with data from PHP. Take a look at Flot or something similar.
I feel like I am so close to successfully switching Jim and Jill in this associative array. I ALSO would like it to be repeatable, so if 'Joe' is added to the end, it will also swap 'Jim' and 'Joe.' Any pointers?
<?php
function jim_is_jill($their_name) {
$first = key($their_name);
foreach ($their_name as $key => $value) {
$lastmaybe = $key;
}
$lastmaybe = $these; // Lastmaybe is Jill
$these = $first;
return $their_name;
}
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
print_r(jim_is_jill($their_name));
?>
CURRENT OUTPUT:
Array
(
[Jim] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jill] => daughter
)
DESIRED OUTPUT:
Array
(
[Jill] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jim] => daughter
)
Considering the array
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
This function will produce :
function array_swap_values($array, $key1, $key2) {
$temp = $array[$key1];
$array[$key1] = $array[$key2];
$array[$key2] = $temp;
return $array;
}
$their_name = array_swap_values($their_name, 'Jim', 'Jill');
// -> array(
// 'Jim' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jill' => 'dad'
// );
Or this function will produce
function array_swap_keys($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key2];
} else if ($key === $key2) {
$ret[$key1] = $array[$key1];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_keys($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'dad'
// );
** Update **
After your last edit, I modified the last function to return what is expected. It is pretty close to the first function, but it preserve the key ordering :
function array_swap_key_value($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key1];
} else if ($key === $key2) {
$ret[$key1] = $array[$key2];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_key_value($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'dad',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'daughter'
// );
First thing, in my experience, it's not wise to rely on the order of an array, if it is not indexed by numbers. There are no tools (correct me if I'm wrong) to switch positions of keys or change keys themselves. It would have to be ugly hack. The only way to rename a key is to remove it and put it back correctly. But that disturbs the order of an array. You'll really have to rebuild the array from scratch, that's an easiest way, as suggested by Yanick, if you really want to do what you want to do. But there's more neat solution. You can make an array with numbered indexes, which you-shall-not-touch. That way, it will stay order. Then put simple small array in each value:
array('name'=> 'Jill, 'relationship'=>'daughter);
That way, you have full control of the order of indexes (thanks to numbered indexes) and you will only have to swap values, which is dead easy.
Or, you can omit those words and give it just numbered indexes everywhere. That way you'll write less but you will have to remember which is which:
array('jill', 'daughter');
is effectively same as:
array(0 => 'Jill', 1 => 'daughter');
So here's the code..
<?php
function swap_first_and_last($their_name) {
//get first and last keys
reset($their_name); // resets the array pointer to beginning
$k_first=key($their_name); // first key
end($their_name);
$k_last=key($their_name); // last key
// swap first and last:
$swap = $their_name[$k_first]['name'];
$their_name[$k_first]['name']=$their_name[$k_last]['name'];
$their_name[$k_last]['name']=$swap;
// note: you can use [0] and [1], if you modify your array that way
return $their_name;
}
// modified array
$their_name = array(
// note, you can omit those 0 => , 1 => ,2,... keys
0 => array('name' => 'Jim', 'relationship' => 'dad'),
1 => array('name' => 'Josh', 'relationship' => 'son'),
2 => array('name' => 'Jamie', 'relationship' => 'mom'),
3 => array('name' => 'Jane', 'relationship' => 'daughter'),
4 => array('name' => 'Jill', 'relationship' => 'daughter')
);
var_dump(swap_first_and_last($their_name));
And the result is:
array (size=5)
0 =>
array (size=2)
'name' => string 'Jill' (length=4)
'relationship' => string 'dad' (length=3)
1 =>
array (size=2)
'name' => string 'Josh' (length=4)
'relationship' => string 'son' (length=3)
2 =>
array (size=2)
'name' => string 'Jamie' (length=5)
'relationship' => string 'mom' (length=3)
3 =>
array (size=2)
'name' => string 'Jane' (length=4)
'relationship' => string 'daughter' (length=8)
4 =>
array (size=2)
'name' => string 'Jim' (length=3)
'relationship' => string 'daughter' (length=8)