I'm using php laravel, Lets suppose below $records is an array and has only 3 records, the foreach loop will run 3 times.
foreach ($records as $record) {
// Here im using query to get logs against each record id.
$logs = "SELECT delivery, COUNT(*) as logs FROM logs where id =
$record['id] group by delivery";
// Run query and it returns array
var_dump($logs)
}
This dump query gets records like this..
1st time
array (size=2)
0 =>
array (size=2)
'delivery' => string '0' (length=1)
'logs' => string '1' (length=1)
1 =>
array (size=2)
'delivery' => string '1' (length=1)
'logs' => string '1' (length=1)
2nd time
array (size=1)
0 =>
array (size=2)
'delivery' => string '1' (length=1)
'logs' => string '1' (length=1)
3rd time
array (size=2)
0 =>
array (size=2)
'delivery' => string '0' (length=1)
'logs' => string '1' (length=1)
1 =>
array (size=2)
'delivery' => string '1' (length=1)
'logs' => string '1' (length=1)
I want to calculate records like
Total SMS; // In above example, total are 5
Total Delivered; // In above example, Delivered are 3
Total Failed: // In above example, Failed are 2
Here is how i'm calculating
If delivery = 0 , it means failed, if delivery = 1, it means delivered, So there are 3 delivered and 2 failed in above scenario.
Here is what i have tried but it not giving me correct result.
$logsSENT = $logsFailed = 0;
foreach ($logs as $log) {
if($log['delivery'] == 1) {
$logsSENT += $log['logs'] * $smsConsumedPerMessage;
}
if($log['delivery'] == 0) {
$logsFailed += $log['logs'] * $smsConsumedPerMessage;
}
}
$total_sms += $logsSENT + $logsFailed;
BTW 'logs' => string '1' (length=1) Logs value can be more than 1, It can be 2, 3 etc..
Secondly, In my IFs I'm multiplying it with 1 for example
$logsSENT = $logs[1]['logs'] * 1; 1 is only for above example, It can be changed later to 2, 3 etc
<?php
$array = array(
array(
array("delivery" => 0, "logs" => 1),
array("delivery" => 1, "logs" => 1)
),
array(
array("delivery" => 1, "logs" => 1)
),
array(
array("delivery" => 0, "logs" => 1),
array("delivery" => 1, "logs" => 1)
)
);
$sum = $deliver = $failed = 0;
foreach ($array as $value) {
$i=$j=1;
foreach ($value as $va) {
if($va['delivery']) {
$deliver = $deliver + $i;
$i++;
} else {
$failed = $failed + $j;
$j++;
}
}
}
echo 'Total:' .($deliver + $failed).'<br>';
echo 'Deliver: '.$deliver.'<br>';
echo 'Failed: '.$failed.'<br>';
?>
Related
I have tried a number of PHP functions like array_unique to merge the arrays I have but that does not work since these are not strings.
The starting output would be this on var_dump( $country_cities );
array (size=3)
0 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7886
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Laurence' (length=8)
'city_name_arabic' => string '3684hdfpfwbhisf' (length=15)
1 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
2 =>
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
The Code below merges the different arrays above.
<?php
// Make the cities unique. Remove duplicates form the inner array.
$uniques = [];
foreach($country_cities as $arr ) {
foreach( $arr as $v) {
if( !in_array($v, $uniques, false) ) {
$uniques[$v['country']] = $v;
}
}
}
var_dump($uniques);
Results logged show the code cuts out some of the arrays.
/Users/..... on line php:74:
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
Please help figure out my error or suggest a better way to fix it.
If I understood you correctly, this should be the result you wanted to achieve.
Each country code will be included once, while the cities (based on post_id) will only be added once.
<?php
$result = [];
$processedIds = [];
foreach ($country_cities as $ccs) {
foreach ($ccs as $cc => $details) {
// If the country has not yet been added to
// the result we create an outer array.
if (!key_exists($cc, $result)) {
$result[$cc] = [];
}
$postId = $details['post_id'];
if (!in_array($postId, $processedIds)) {
// Add the unique city to country's collection
$result[$cc][] = $details;
// Keep track of the post_id key.
$processedIds[] = $postId;
}
}
}
print_r($result);
<?php
//...
$uniques = [];
foreach($country_cities as $data ) {
foreach( $data as $countryCode => $item) {
if( !array_key_exists($countryCode, $uniques) ) {
$uniques[$countryCode] = []; //Create an empty array
}
$targetArray = &$uniques[$countryCode];
if( !array_key_exists($item['post_id'], $targetArray) ) {
$targetArray[$item['post_id']] = $item; //Create an empty array
}
}
}
Maybe this code will help?
I have a problem on $weight_class_title.
When the data is saved it wrote in the database array.
Tk.
the result of var_dump($sql_data_array);
array (size=4)
'weight_class_title' =>
array (size=1)
'weight_class_title' => string 'tt' (length=2)
'weight_class_key' => string 'pound' (length=5)
'weight_class_id' => int 5
'language_id' => int 1
array (size=4)
'weight_class_title' =>
array (size=1)
'weight_class_title' => string 'tt' (length=2)
'weight_class_key' => string 'pound' (length=5)
'weight_class_id' => int 5
'language_id' => int 2
public function execute() {
$CLICSHOPPING_Language = Registry::get('Language');
$CLICSHOPPING_Db = Registry::get('Db');
$languages = $CLICSHOPPING_Language->getLanguages();
$QlastId = $CLICSHOPPING_Db->prepare('select weight_class_id
from :table_weight_classes
order by weight_class_id desc
limit 1');
$QlastId->execute();
$weight_class_id = $QlastId->valueInt('weight_class_id') + 1;
$weight_class_key = $_POST['weight_class_key'];
for ($i=0, $n=count($languages); $i<$n; $i++) {
$weight_class_title_array = $_POST['weight_class_title'];
$language_id = $languages[$i]['id'];
$weight_class_title_array = ['weight_class_title' => HTML::sanitize($weight_class_title_array[$language_id])];
$sql_data_array = ['weight_class_title' => $weight_class_title_array];
$insert_sql_data = ['weight_class_key' => $weight_class_key,
'weight_class_id' => $weight_class_id,
'language_id' => $languages[$i]['id']
];
$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
$this->app->db->save('weight_classes', $sql_data_array);
}
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);
I have a json file with this below format structure.
[
{
"name":"banana",
"type":"fruit",
"rate":10
},
{
"name":"orange",
"type":"fruit",
"rate":20
},
{
"name":"apple",
"type":"fruit",
"rate":30
}
]
I would like to update the rate of the fruit by +1 when i match a search for it.
1 . Read the json file
$json_file = file_get_contents('fruits.txt');
2 . Decoded the json file
$fruit_list=json_decode($json_file,true);
VarDumping the Decoded json file is like this
array (size=3)
0 =>
array (size=3)
'name' => string 'banana' (length=6)
'type' => string 'fruit' (length=5)
'rate' => int 10
1 =>
array (size=3)
'name' => string 'orange' (length=6)
'type' => string 'fruit' (length=5)
'rate' => int 20
2 =>
array (size=3)
'name' => string 'apple' (length=5)
'type' => string 'fruit' (length=5)
'rate' => int 30
Wrote a search function to search the array for fruit name
function search_by_key_and_value($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search_by_key_and_value($subarray, $key, $value));
}
return $results;
}
$result = search_by_key_and_value($fruit_list,"name",apple);
when the function is supplied with fruit name the whole of json file is searched and the RESULT_MATCH is printed var_dump($result) is like this below
array (size=1)
0 =>
array (size=3)
'name' => string 'apple' (length=5)
'type' => string 'fruit' (length=5)
'rate' => int 30
How can i find the array index number as the result of array index is 0 in the result but its position in the main file point no 3 is indexed at 2 or at-least how can i update the matched retsult rate directly ?
I've got the current array
array
161 =>
array
'cat_id' => string '5' (length=1)
'temp_id' => string '2' (length=1)
'prod_id' => string '44' (length=2)
162 =>
array
'cat_id' => string '3' (length=1)
'temp_id' => string '2' (length=1)
'prod_id' => string '44' (length=2)
164 =>
array
'cat_id' => string '2' (length=1)
'temp_id' => string '2' (lenth=1)
'prod_id' => string '45' (length=2)
I am using this function to remove the duplicate array values:
function removeDupes($array) {
$temp = array();
foreach ($array as $k => &$v) {
if (in_array($v['prod_id'],$temp)) {
unset($array[$k]);
}
$temp[] = $v['prod_id'];
}
return $array;
}
This removes any duplicate value in the array if prod_id is a duplicate in a previous array.
I'd like to maintain the full category id list for the product and at the moment, these get deleted when I unset the entire key=>value pair.
Has anyone got any ideas how I could achieve this?
EDIT as per comment:
I'm looking for something like this as a result:
array
161 =>
'cat_id' => array('5','3')
'prod_id' => 44
So I have removed the duplicate array entry that duplicated the product ID but maintained the Category ID's. I hope that helps.
Maybe something like this:
$input = array(); // define your array
$output = array(); // here will be output
$temp = array();
foreach($input as $key => $value)
{
if (isset($temp[$value['prod_id']]))
{
$output[$temp[$value['prod_id']]]['cat_id'][] = $value['cat_id'];
}
else
{
$output[$key] = array(
'cat_id' => array($value['cat_id']),
'prod_id' => $value['prod_id']
);
$temp[$value['prod_id']] = $key;
}
}
First thing that came to my mind is to iterate over your structure, build a helping structure of array_index => prod_id of first occurrence (for this example array(44 => 161, 45 => 164)). You remove every but first and at the same time add prod_id to the first one found.