How to add values in array in php? - php

I have two variables: $report1 and $report2
function overallStats($startdate, $enddate) {
$reports1 = $analytic_report->reports->query('contentOwner==first',
$startdate, $enddate, 'views,earnings', array(
'dimensions' => 'day',
'filters' => 'claimedStatus==claimed',
'sort' => 'day'
));
$reports2 = $analytic_report->reports->query('contentOwner==second',
$startdate, $enddate, 'views,earnings', array(
'dimensions' => 'day',
'filters' => 'claimedStatus==claimed',
'sort' => 'day'
));
$reports = array_merge($reports1, $reports2);
}
function second(){
$overallrawstats = $this->overallStats(date('Y-m-d', strtotime('9 days ago')), date('Y-m-d', strtotime('yesterday')));
if (!empty($overallrawstats)) {
$overallstats = array();
foreach($overallrawstats as $p=>$o) {
$overallstats[] = array(
recorddate => $o[0],
views => $o[1],
revenue => $o[2]
);
}
}
}
I want to get a third array which merged all the values of these two array, But when I get third merged array in it views and earnings should be add of these two array. How can I get it?

assuming both arrays are equally of length:
$report3 = array();
foreach ($report1 as $index => $value) {
array_push($report3, (int) $value + (int) $report2[$index]);
}

Related

Search Arrays to Multidimensional Array

I have 2 dimensional array like
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
result: array('Cancer Webinar','Company Anniversary');
The function call search from array list ($look) then find it to $events.
From the code above shoud return:
array('Cancer Webinar','Company Anniversary');
If the second array will just search by date use the following code
function search_from_array($array, $events) {
$result = [];
foreach($events as $event) {
if(in_array($event['date'], $array)) {
array_push($result, $event['desc']);
}
}
echo json_encode($result);
}
search_from_array($look, $events);
you can develop it more to can search with any key in the multidimensional array.
in case you want to search but many keys just add OR in the condition and make the same code for other keys like this
if(in_array($event['date'], $array) || in_array($event['desc'], $array))
You can make $look a dict, then check if the date key exist.
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
$look_dic = array_flip($look);
foreach($events as $event){
if(isset($look_dic[$event["date"]])){
$result[] = $event["desc"];
}
}
var_dump($result);

Call each value from array of an object

I have function in class, which returns array with 4 3-4 rows. I have to use each value from related row in table values. I can print builded function atrray, and can print on parent file, but can not get values for elements for each row. Here is my class file:
<?php
class Anyclass
{
public function $monthly($array)
{
.
.
.
}
public function myfunction($array)
{
foreach ($ShowMonths as $duration) {
$array['Credit']['downpayment'] = 0;
$array['Credit']['duration'] = $duration;
$monthly = $this->monthly($array);
$Table['Options'][] = array(
'downpayment' => $array['Credit']['downpayment'],
'duration' => $array['Credit']['duration'],
'monthly' => $monthly,
'total' => $monthly * $array['Credit']['duration'] + $array['Credit']['downpayment']
);
}
print_r($Table);
}
}
Here is my main file
include_once('mypathtofile/FileWithClass.php');
$Cll = new NewOne();
$array = array(
'Rule' => array(
'rule_id' => 1,
'rule_name' => 'Mobile phones',
'interest' => 0.01,
'comission' => 0.01,
'best_offer_downpayment' => 0.5,
'best_offer_duration' => 6
),
'Product' => array(
'product_id' => 1,
'category_id' => 1,
'manufacturer_id' => 1,
'product_price' => 500
),
'Credit' => array(
'downpayment' => 100,
'duration' => 6
)
);
$prtst = $Cll->myfunction($array);
How can I call each elemet for each row?
I'm not sure what you are trying to do, but if you need to get each value in a multidimensional array - you can use recursion:
function get_value($array){
foreach($array as $item){
if(is_array($item)){
get_value($item);
} else {
echo $item;
}
}
}

PHP MVC query to get all existing rows is returning only 1 row

I have a working query but its only returning 1 row - where or what can I do to return all existing rows?
Model:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return array(
'info_id' => $info_query->row['info_id'],
'name' => $info_query->row['name'],
'amount' => $info_query->row['amount'],
'date_start' => $info_query->row['date_start'],
'date_end' => $info_query->row['date_end'],
'status' => $info_query->row['status'],
'date_added' => $info_query->row['date_added']
);
}
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
if ($info_options){
$json['info_options'] = array();
$json['info_options'][] = array(
'info_id' => $info_options['info_id'],
'name' => $info_options['name'],
'amount' => $info_options['amount'],
'date_start' => $info_options['date_start'],
'date_end' => $info_options['date_end'],
'status' => $info_options['status'],
'date_added' => $info_options['date_added']
);
}
When I try foreach() in the controller, I still only get one row.:
foreach ($info_options as $info) {
var_dump($info_options['name']);exit;
//var_dump($info_options['name']); results: Warning: Illegal string offset 'name'
}
In the model, when I dump:
$info_query I get 9 -- which is all of the rows I'm expecting.
Not particularly certain what I'm missing or doing wrong.
You're not looping over the result. Not in model nor in the controller. Though I don't know why you'd do this twice. Maybe I'm just not understanding your code.
Model:
$data = [];
if ($info_query->num_rows){
foreach ($info_query->result() as $row) {
$data[] = array(
'info_id' => $row['info_id'],
'name' => $row['name'],
'amount' => $row['amount'],
'date_start' => $row['date_start'],
'date_end' => $row['date_end'],
'status' => $row['status'],
'date_added' => $row['date_added']
);
}
return $data;
}
Controller:
$info_options = $this->model_extension_total_info->getInfo();
$json['info_options'] = array();
if ($info_options){
foreach ($info_options as $info) {
$json['info_options'][] = array(
'info_id' => $info['info_id'],
'name' => $info['name'],
'amount' => $info['amount'],
'date_start' => $info['date_start'],
'date_end' => $info['date_end'],
'status' => $info['status'],
'date_added' => $info['date_added']
);
}
}
Technically, you don't have to loop at all. You can just:
public function getInfo() {
$info_query = $this->db->query("SELECT * FROM `km_info` WHERE ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) AND status = '1'");
if ($info_query->num_rows){
return $info_query->result();
}
else
{
return false;
}
}
and
$info_options = $this->model_extension_total_info->getInfo();
// and that's it, just do whatever you need with $info_options

How to extract the relevant elements from this array of associative arrays?

I have the following challenging array of associative arrays in php.
array(
(int) 0 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name1'
)
),
(int) 1 => array(
'table' => array(
'venue' => 'venue1',
'name' => 'name2'
)
),
(int) 2 => array(
'table' => array(
'venue' => 'venue2',
'name' => 'name3'
)
),
(int) 3 => array(
'table' => array(
'venue' => 'venue3',
'name' => 'name4'
)
)
)
I want to extract a list of relevant names out based on the venue. I would like to implement a function ExtractNameArray($venue) such that when $venue=='venue1', the returned array will look like array('name1', 'name2')
I have been cracking my head over this. I am starting with $foreach and am stuck. How can this be done in php? Thank you very much.
first, you have to pass the array with the data to the function
second, the name of the function should start with lower character (php conventions)
try this
function extractNameArray($array, $venue) {
$results = array();
foreach($array as $key=>$value) {
if(isset($value['table']['venue'])&&$value['table']['venue']==$venue) {
isset($value['table']['name']) && $results[] = $value['table']['name'];
}
}
return $results;
}
function ExtractNameArray($venue)
{
$array = array(); // your array
$return_array = array();
foreach($array as $arr)
{
foreach($arr['table'] as $table)
{
if($table['venue'] == $venue)
{
$return_array[]['name'] = $table['name'];
}
}
}
return $return_array;
}
You must define $array with you array. Good Luck

How to compare array a with b and create new arrays c (items in a and b), d (items in a, not in b), and e (items in b, not in a)?

Consider the following arrays. They represent the top-5 performing employees for yesterday and today:
$yesterday = array(
6 => array('name' => 'Tod', 'score' => 9.5),
12 => array('name' => 'Jim', 'score' => 7.3),
18 => array('name' => 'Bob', 'score' => 8.4),
7 => array('name' => 'Jan', 'score' => 6.2),
20 => array('name' => 'Sam', 'score' => 6.0),
);
$today = array(
6 => array('name' => 'Tod', 'score' => 9.1),
9 => array('name' => 'Jef', 'score' => 9.3),
35 => array('name' => 'Axl', 'score' => 7.6),
7 => array('name' => 'Jan', 'score' => 6.5),
41 => array('name' => 'Ted', 'score' => 8.0),
);
I need 3 new arrays compiled from the above: $stay holding employees who were in the top-5 yesterday, and still are today, $gone, holding employees who were in the top-5 yesterday, but are not anymore, and $new, holding newcomers to $todays top-5 list:
// notice that the scores in $stay come from $today, not $yesterday
// also notice that index keys are maintained
$stay = array(
6 => array('name' => 'Tod', 'score' => 9.1),
7 => array('name' => 'Jan', 'score' => 6.5)
);
$gone = array(
12 => array('name' => 'Jim', 'score' => 7.3),
18 => array('name' => 'Bob', 'score' => 8.4),
20 => array('name' => 'Sam', 'score' => 6.0)
);
$new = array(
9 => array('name' => 'Jef', 'score' => 9.3),
35 => array('name' => 'Axl', 'score' => 7.6),
41 => array('name' => 'Ted', 'score' => 8.0)
);
I have no clue on how to build the logic here. I started with a loop, but didn't get far. I believe it should be something like this. Could you help me get this right?
for ($i = 0; $i < count($yesterday); $i++) {
// I'm comparing key numbers, but not key values
// how do I compare key values?
if (in_array($yesterday[$i], $today) {
// add to $stay array
}
else {
// add to $gone array
}
}
for ($i = 0; $i < count($today); $i++) {
if (!in_array($today[$i], $yesterday) {
// add to $new array
}
}
P.S. I don't know if this is helpfull, but $yesterday and $today are always of equal length (in this case, 5 items, but other scenarios are possible in which both arrays hold 7 or 10 items for instance). The combined items of $stay and $new logically are always equal to the number of items in either $yesterday or $today :-)
https://www.php.net/manual/function.array-intersect.php
https://www.php.net/manual/function.array-diff.php
$c = array_intersect($a, $b);
$d = array_diff($a, $b);
$e = array_diff($b, $a);
This can be accomplished using just a few of PHP's many powerful array functions:
$stay = array_intersect_assoc($yesterday, $today);
$gone = array_diff_assoc($yesterday, $today);
$new = array_diff_assoc($today, $yesterday);
I think this should work but isnt the fastest method to do this i think.
$stay = array();
$gone = array();
$new = array();
$found = false;
foreach($yesterday as $yKey)
{
$found = false;
foreach($today as $tKey)
{
if($tKey['name'] == $yKey['name'])
{
$found = true;
$stay[]['name'] = $tKey['name'];
break;
}
else
{
$found = false;
}
}
if($found == false)
{
$gone[]['name'] = $yKey['name'];
}
}
foreach($today as $tKey)
{
$found = false;
foreach($yesterday as $yKey){
if($yKey['name'] == $tKey['name'])
{
$found = true;
break;
}
else{
$found = false;
}
}
if($found == false)
{
$gone[]['name'] = $tKey['name'];
}
}

Categories