|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2003-06-02 15:55 UTC] prof_moriarty at veryfast dot biz
This is tricky to explain, but easy to understand.
At present there's a function: array_sum that adds up all the values in an array.
I would like to suggest somthing similar, and at the same time intrinsically different.
The ability to sum up an elements value in a multi-dimensional array.
Example multi-dim-array:
array (
'box1' =>
array (
'height' => 5,
'length' => 10,
'width' => 3.5,
),
'box2' =>
array (
'height' => 17,
'length' => 9,
'width' => 8,
),
)
The above array contains two boxes and a few dimensions...
What do i do if i want to work out the combined height of the boxes (to see if they can fit into a space)? I could write a little function to do it sure.
But i figure quite a few other people could use this little function too, so i'll suggest it to you.
some clarification, using the above example array.
the syntax for the function could be:
mixed proposed_function(array input, string element_name)
An example of it in use:
$result = proposed_function($array_to_manipulate, 'height');
echo $result;
The result would be:
22 //becase 5 + 17 = 22 :)
I hope thats clear...
Keep up the good work folks... :)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 23:00:02 2025 UTC |
Perhaps someone else will be motivated enough to implement this (feel free to write it yourself and submit a patch to internals@lists.php.net) but here's some userspace code which accomplishes what you want. $total = 0; foreach($array_to_manipulate as $key => $value) if ($key == 'height') $total += $value; Which I'm sure you can see is easy enough to wrap in a function.sorry, i can't code in C/++, so can't do it myself. :) however that code can't work (i just tested it to make sure). You missed a layer of the looping. It should be: $total = 0; foreach($array_to_manipulate as $boxes => $box_arrays){ foreach($box_arrays as $key=> $value){ if ($key == 'height') { $total += $value; } } } That should work..... As you can see, with sizeable arrays, it could go around quite a few times... Which (from a performance front) would be better if it was done in c(++).... Hint Hint... ;)This should be on php-general by now, but... Why the inner foreach? According to the stated problem, you *know* which key you're looking for, so why not go straight for it? So... function proposed_function($array, $key) { $total = 0; foreach($array as $subarr) if (isset($subarr[$key])) $total += $subarr[$key]; return $total; }