Summing up Associative array - php

Array(
[User1] => 162
[User2] => 15
[User3] => 158
[User4] => 92
[User5] => 2
[User6] => 3
[User7] => 2
[User8] => 25
[User9] => 10
[User10] => 6
[User11] => 14
)
Above is my array of arrays. This list is completely dynamic - the values(numbers) change, and all of the Users are not numbers, but have actual user names - they don't say User1, they say instead like TomJohnson4512 - on and on, they're all different
All I want to do, is some sort of loop to add up and display/print/echo the values. I don't care about the user names, all I want is a sum of the values.
Any ideas?

All you need to do is use array_sum ( $array ) so assuming your array is called $array, do this
$total = array_sum ( $array );

Related

how to create the multiple values with same key in array in php [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed last month.
I have an array with multiple key.
Array 1
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Output
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
Expected Output
$age = array("value"=>"35", "value"=>"37", "value"=>"43");
Array ( [value] => 35 [value] => 37 [value] => 43 )
You can't
Indeed, array keys must be unique. Otherwise, what should the program output when you try to access value ?
But ...
If you need to store a list of value for one key, you can use array of arrays.
$array = array("value" => array());
array_push($array["value"], 35, 40, 53);
print_r($array)
And the output will be:
Array
(
[value] => Array
(
[0] => 35
[1] => 40
[2] => 53
)
)
Only way is to turn this array into 2D array:
$age = array(
array("value" => "35"),
array("value" => "37"),
array("value" => "43")
);
-- Output --
Array
(
[0] => Array
(
[value] => 35
)
[1] => Array
(
[value] => 37
)
[2] => Array
(
[value] => 43
)
)
-- Usage --
$age[0]['value'];
$age[1]['value'];
$age[2]['value'];
But it completely depends if $age array is in our control and can be changed.
You can't
Array keys must be unique.
http://php.net/manual/en/language.types.array.php
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
Yes, array key should be unique. So, whatever you are asking it's not possible. Can you tell us what's requirements? So that, people can suggest any alternate solution.
This cannot be possible with native php arrays. What you need is a multimap, and you can find several implementations of it on github.
For example: link
EDIT: the link above is an interface. you need to include also link2

Add new pair key => value into array from another array

I have tried array_merge, to merge them based on similar keys, array_push, various [] combinations but I just can't figure this one out. I have two arrays, one looks like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
)
And, I want to add one new key to each of 650, 651, 652... sub-arrays (I will call the key 'Barva'), and short set of values from another array (10 total) to periodically loop in each sub-array under that key, so that 1st and 11th value is the same, 2nd and 12th is the same and so on, and all to be under the same key.
It would look like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
[Barva] => 1
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
[Barva] => 2
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
[Barva] => 3
)
...
[660] => Array
(
[Kampan] => ...
[ZelvaUL] => ...
[ZelvaOV] => ...
[OCS] => ...
[Rezim] => ...
[Barva] => 1
)
Seriously, I am out of ideas...
Thanks for any help guys.
edit:
This is the array I want to add:
$camp_barvy = array(
'background-color:#ffffff;color:#111111;',
'background-color:#ffcc02;color:#111111;',
'background-color:#ff7700;color:#ffffff;',
'background-color:#ff2323;color:#ffffff;',
'background-color:#ff00aa;color:#ffffff;',
'background-color:#aa44ff;color:#ffffff;',
'background-color:#1188ff;color:#ffffff;',
'background-color:#11ddff;color:#111111;',
'background-color:#00dd77;color:#111111;',
'background-color:#119911;color:#ffffff;'
);
I wanna do some large and extensive conditioned formatting and both javascript and php if statement make the loading too slow, so I figured I will make the format part of the array I already look in for the values based on which I choose the desired format.
Really, its the best choice :)
What you want to do is iterate over each value in your "input" array and insert in it a new value taken from your "data" array (those 10 values you mention). When your data array is exhausted, you want to loop back to its start and continue inserting values in the "input" array elements.
So you want something like:
foreach ($input as &$row) {
$row['Brava'] = $next_item_from_data_array;
}
which leaves just the problem of how to easily iterate and loop over the data array.
A convenient and modern way of doing this is by using the built-in SPL iterators: an ArrayIterator for your data array and an InfiniteIterator around that so that you loop back to the start automatically as required. This way you also don't have to assume anything about your data array (such as if it is numerically indexed or not).
For example:
$dataIterator = new InfiniteIterator(new ArrayIterator($data));
$dataIterator->rewind();
foreach ($input as &$row) {
$row['Brava'] = $dataIterator->current();
$dataIterator->next();
}
// After iterating by reference (&$row) it is always a good idea to unset
// the reference so that you don't reuse it later on by mistake -- although
// this is not required and the program will work correctly without it.
unset($row);
See it in action.

Change Array Keys and sort them via PHP

I looked at different options how to sort arrays. But somehow none of the given PHP commands suit my purpose.
Example - I have an array like this :
Array
(
[abc] => Array
(
[2] => 2
[3] => 3
[5] => 5
)
)
But I want to change the array to
[0] => 2
[1] => 3
[2] => 5
In other words I want to remove all keys - sort all values from LOW to HIGH and then just give em the keys from zero to X
It's much easier to work with such an array if you want to use some loops like (for, while, etc.)
Just use sort and array_values.
<?php
$array = array(
'abc' => array(
2 => 2,
5 => 5,
3 => 3,
),
);
sort($array['abc']);
$array = array_values($array['abc']);
print_r($array);
I've popped up an example at http://3v4l.org/51naW

Returning Keys and Values from Array

Can anyone please help me out with that one. I'm getting the locale of Facebook page fans. The output from Facebook is in JSON format. After I json_decode($fb_output) I end up with array below. I'd like to echo a list with the top 10 languages (or all if there are less than 10) and the value in the key(number of people who speak that language). So far I've unsuccessfully tried to get it with foreach ($fb_output $key => $value)
Here is the array:
Array (
[0] => stdClass Object (
[value] => stdClass Object (
[de_DE] => 8527
[en_US] => 313
[en_GB] => 147
[tr_TR] => 106
[it_IT] => 79
[sr_RS] => 25
[hu_HU] => 24
[es_ES] => 15
[bs_BA] => 12
[es_LA] => 12
[sk_SK] => 11
[ro_RO] => 10
[ru_RU] => 9
[pt_BR] => 9
[nl_NL] => 8
[hr_HR] => 8
[fr_FR] => 7
[sv_SE] => 5
[cs_CZ] => 5
[bg_BG] => 5
)
[end_time] => 2012-03-05T08:00:00+0000 ) )
The number of keys in this array varies from user to user so it'd need to be flexible.
How about something like this:
$topTen = array_slice(array_keys( (array) $fb_output[0]->value ), 0, 10);
What it does:
Transforms the stdClass Object into an native array. ((array) operator)
Turns that array into another array, containing only its keys. (array_keys() function)
Extracts the first ten entries of that array. (array_slice() function)
If you want to extract the top ten including their values, skip the array_keys part and make sure, that the keys of the array don't get mixed up while slicing it (4th parameter of that function, see the docs for more information):
$topTen = array_slice( (array) $fb_output[0]->value, 0, 10, true);
echo $topTen['en_GB']; // 147

PHP recursion function to show valid combinations of array values

I have a PHP array that looks like this:
Array
(
[340] => Array
(
[1] => 1
[2] => 18
[3] => 23
)
[341] => Array
(
[1] => 1
[2] => 17
[3] => 23
)
[342] => Array
(
[1] => 1
[2] => 16
[3] => 23
)
[343] => Array
)
The array is actually longer and contains about 40 elements. There will be other arrays that contain a different number of child elements. The array is formatted as
productID => array (
$attributeID => attributeValueID,
$attributeID => attributeValueID,
$attributeID => attributeValueID
)
What I need is an array that shows the valid values for all other attributes. The output array might looks something like
Array
(
18 => array(
1 => array(
11, 12, 13, 14, 15
)
2 => array(
19, 20, 21, 22
)
)
19 => array(
1 => array(
11, 13, 14, 15
)
2 => array(
21, 22
)
)
The format of this array is
attributeValueID => array(
attributeID => attributeValues,
attributeID => attributeValues
)
I've been working with some recursion functions but I've only been able to get a list of every possible combination between all the values which isn't what I need. Any help would be greatly appreciated.
Clarification on what I mean by "valid" values: What the 1, 2, and 3 values represent here are color, size, and length. The ultimate goal here is to create a series of javascript arrays I'll use to update options on the page when a user selects values. For example when they select the color black I need to update the sizes and lengths on the page to reflect only sizes and lengths available in black. I can create the arrays manually but this is not a good solution.
Ok, if I get that right now, you have Products with four attributes: id, color, size and length, which you represent as
[product_id] => array (
1 => [color_id],
2 => [size_id],
3 => [length_id]
)
Personally, I find this structure somewhat clumsy. Product id should be inside the array, because it is an attribute of product. Also, using index numbers instead of the property names, makes your products difficult to understand.
Now, what you want to do is, find all possible combinations of one of the attributes, e.g. all size_id and length_id when the user selects color_id for e.g. black.
You could do that with a finder method:
function findCombinationsByColorId($color_id, $products)
{
$combos = array($color_id => array(
'sizes' => array(),
'lengths' => array(),
'products' => array()
));
foreach($products as $productId => $product)
{
if($product[1] === $color_id) {
$combos['sizes'][] = $product[2];
$combos['lengths'][] = $product[3];
$combos['products'][] = $productId;
}
}
return $combos;
}
Now, when you need to find all combinations for black and black is color_id of 0, you'd do findCombinationsByColorId(0, $productArray) and it would return an array holding all possible sizes, lengths and product Ids for this color.
You'd write additional functions for getting combinations by the other attributes. You could make the finder method generic, but I leave that up to you to figure out how.
What I dont get is why you are sorting this on the array level at all. I assume you get the possible products from somewhere, e.g. a database. So why not get the combos from there. That would probably be as easy as SELECT size_id, length_id, product_id from products where color_id = 0.
Assuming the output should actually be:
attributeValueID => array(
attributeID => productID,
attributeID => productID
)
(If not where do the attribute values come from?)
Recursion would not be needed, just something along these lines to re-jig the array:
$products = array( 340 => array(
1 => 1,
2 => 18,
3 => 23
),
341 => array(
1 => 1,
2 => 17,
3 => 23
),
342 => array(
1 => 1,
2 => 16,
3 => 23
),
343 => array()
);
$output = array();
foreach($products as $product_id=>$attributes){
$attribute_id;
foreach($attributes as $attribute_id=>$attribute_value){
$output[$attribute_value][$attribute_id][] = $product_id;
}
// optionaly filter for dup product ids
//$output[$attribute_value][$attribute_id] = array_unique($output[$attribute_value][$attribute_id], SORT_NUMERIC);
}
The answer Gordon supplied is closest to what I'm looking for but is not very efficient given the way my initial array was formatted. Though I can't recall why now, my original purpose in using arrays was to avoid having to make a new query each time someone selects an option. The easy solution is just to proceed with the queries so that's what I'll do.

Categories