add values of array in php - php

Hi i know its very simple but im stuck in this.
Im fetching data by using join from database.. Now i got the values in array. i want to add these two value in a variable.
Code is below..
$sql = "SELECT event_details.max_team_size FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryAll();
$array has got the values like this..
Array
(
[0] => Array
(
[max_team_size] => 6
)
[1] => Array
(
[max_team_size] => 8
)
)
I want to add these two max_team_size into a single variable and use that later to compare.

$sum = 0;
foreach($array as $data){
$sum += $data->max_team_size;
}
echo $sum;

Sum you can get from SQL also by using SUM function
SELECT SUM(event_details.max_team_size) FROM booking_details...
In Yii the solution will be
$sql = "SELECT SUM(event_details.max_team_size) as total FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryRow();
In PHP to sum particular key in single array you can convert it to single array by using array_column function and then use sum function
$array = array_column($array, 'max_team_size');
$total = array_sum($array);
Note: array_column will work PHP >= 5.5, for PHP < 5.5 you can use foreach loop

Define an empty array like this:
$maxArr = array();
You can run a foreach loop for your array now and add variable.
Like this:
foreach($gotArr as $key=>$val){
}

Related

PHP create 1 array of 4 arrays ordered by index

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}

Get Sum of Values using array_combine?

I am trying to count the total sum of values using array_combine. I have the duplicate key also, for example i have the array of emailid and array of product price.
$data1 = array("email1#example.com","email2#example.com","email1#example.com");
and $data2 = array("100","200","300");
Now in $data1 i have two duplicate values as email1#example.com
I am trying to use array_combine() It ignore the duplicate values and add the new one
I get this result as
email1#example.com => 300;
email2#example.com => 200;
But i want the result should be
email1#example.com => (400)100+300;
email2#example.com => 200;
Not sure how to get this result with array_combine Is something any alternatives to achieve this ?
Any Suggestion would be great.
Write a simple loop:
$result = array();
foreach ($data1 as $i => $v) {
if (!isset($result[$v])) {
$result[$v] = 0;
}
$result[$v] += $data2[$i];
}

Join string and variable to get another variable in PHP

Sorry if this has already been asked, but it's hard to search for it... I tried googlin this topic without success.
What I want to do is this:
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo $chosenTheme [0];
I want to join the $layoutColor variable with the word "colors" in order to get the variable $colors2.
How do I do that?
Thanks.
You're best off approaching this by just combining all your options into a single multi-dimensional array:
$layoutColor = 2;
$colors = array();
$colors[1] = array ("F57171", "FACCCC");
$colors[2] = array ("FF9900", "FFC66F");
$chosenTheme = $colors[$layoutColor];
echo $chosenTheme [0];
Try this:
<?php
$layoutColor = 2;
$colors1 = array ("F57171", "FACCCC");
$colors2 = array ("FF9900", "FFC66F");
$chosenTheme = "colors".$layoutColor;
echo ${$chosenTheme}[0];
Prints:
FF9900
I think you can simplify this using multi dimensional arrays:
$colors = array(
array ("F57171", "FACCCC"),
array ("FF9900", "FFC66F")
);
So...
echo $colors[0];
Or you can user variable variables:
$chosenTheme = ${"colors".$layoutColor};
You may try this
$layoutColor = 2;
$$colors2 = "colors".$layoutColor;
So you'll get $colors2 variable
print_r($colors2); // Array ( [0] => FF9900 [1] => FFC66F )
Notice the double $, that will keep the variable name in the variable.
Try with:
$layoutColor = 2;
$string = "color";
echo $$string.$layoutColor;
You need to use dynamic variables
$$chosenTheme = "colors".$layoutColor;
then access the array by using this variable
$chosenTheme
This might not be an answer to your question but, depending on your specific context, try something like this:
$layoutColor = 2;
$colors = array (
Array("F57171", "FACCCC"),
Array ("FF9900", "FFC66F")
);
echo $colors[$layoutColor][0];
A multi dimensional array is a lot easier to read

Insert array data into database

I'm trying to insert array into database. Why don't this work?
$array_zone = array();
$array_data = array();
while($row = mysql_fetch_array($keputusan1)){
$array_zone[] = $row['zone'];
$array_data[] = $row['data'];
}
echo "<pre>";
print_r($array_zone);
echo "<br>";
print_r($array_data);
echo "</pre>";
$list_zone = implode(",", $array_zone);
$list_data = implode(",", $array_data);
for($i = 0; $i < 4; $i++)
{
mysql_query("INSERT INTO `db`.`table1` (`id`, `domain`) VALUES ('$list_zone', '$list_data')");
}
Array output before implode:
Array
(
[0] => 270
[1] => 270
[2] => 255
[3] => 255
)
Array
(
[0] => ok.com.
[1] => lo.com.
[2] => i.com.
[3] => k.com.
)
Result I'm getting:
0 key should go with data in 0 key and 1 key should go with data in 1 key and so on... Help me please. Thank you.
You can use INSERT ... SELECT. The result returned in $keputusan1 is a SELECT query. And it certainly returns zone and data columns. Say the query is SELECT zone, data, columns ... FROM tbl1.
If you use INSERT ... SELECT the new query would be
INSERT INTO `db`.`table1` (`id`, `domain`) SELECT zone, data FROM tbl1";
This will SELECT first then INSERT it in one shot.
The problems with your code are
4 SQL statements. It should be 1.
You should use $array_zone and $array_data instead of $list_zone and $list_data if for loop is used. But it should not be as of step 1.
It seems to me, that you just forgot to use the loop-index ($i) within the loop
to access the arrays elements:
#!/usr/bin/php
<?php
$array_zone = array('a','b','c','d');
$array_data = array('1','2','3','4');
print_r($array_zone);
print_r($array_data);
for($i = 0; $i < count($array_zone); $i++)
{
echo("INSERT INTO `db`.`table1` (`id`, `domain`) VALUES ('$array_zone[$i]', '$array_data[$i]')\n");
}
?>
Now replace that echo with your mysql_query call and remove the '\n' at the end...
Your list_zone (really array_zone) is enclosed in a single set of single quotes, so you're passing one long string. And you're doing it four times. Pass it one pair of values at a time.
Are you sure you want to do this in that way? Probably a good idea to try the serialize() function instead of the implode. http://php.net/manual/en/function.serialize.php
Maybe an even better idea to use JSON for this task. http://php.net/manual/en/function.json-encode.php

PHP in_array isn't finding a value that is there

I have an array called $friend_array. When I print_r($friend_array) it looks like this:
Array ( [0] => 3,2,5 )
I also have a variable called $uid that is being pulled from the url.
On the page I'm testing, $uid has a value of 3 so it is in the array.
However, the following is saying that it isn't there:
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.
What am I doing wrong? Any help would be greatly appreciated!
Output of
Array ( [0] => 3,2,5 )
... would be produced if the array was created by something like this:
$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);
Based on your question, I don't think this is what you meant to do.
If you want to add three values into the first three indexes of the array, do the following:
$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');
or, as a shorthand for array_push():
$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';
Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:
// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);
if(in_array($uid, $friend_array)){
$is_friend = true;
}else{
$is_friend = false;
}
Working example
Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.
Example:
$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;
Your above if statement will then work correctly.

Categories