Click here to Skip to main content
15,878,996 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here's the situation:

I have 2 arrays:

PHP
Array(
    [0] => Person1
    [1] => Person1
    [2] => Person3
)


PHP
Array(
    [0] => 100.00
    [1] => 150.25
    [2] => 157.15
)


Now, my question is: How do I add array values from the second array, as they belong to Person 1 in the first array ? It should output like this:

PHP
Array(
    [0] => 250.25 // for Person1 in the first array
    [1] => 157.15 // for Person2 in the first array
)


I am not finding any solution for it.. Kindly help me out. Please.
Posted
Updated 18-Jan-15 23:45pm
v2
Comments
Joezer BH 19-Jan-15 5:49am    
How do you know which elements in the second array are relating to a specific person?
Mehul Bawadia 19-Jan-15 6:02am    
It is because, I have set them in that order only.
Sinisa Hajnal 19-Jan-15 6:03am    
As-is, you cannot. Since you don't know which element belongs to which person. See the solution.

It cannot work this way. As it is, there is no relationship between the arrays. Instead, you should use associative array[^], which is a type of array consisting of name-value pairs. see example:
PHP
<?php
$first = array("Person1"=>"250.25", "Person2"=>"157.15");
$second = array("Person1"=>"100.00");

    foreach($first as $key1 => $value1) {
            foreach($second as $key2 => $value2) {
               $third[$key1] = $value1;
               if ($key1 == $key2){
                    $third[$key1] +=  $value2;
                    break;
               }
           }
    }

    foreach($third as $key3 => $value3) {
            echo $key3."=".$value3;
            echo "<br>";
    }
?>
 
Share this answer
 
v2
The solution would be to have this number array in person class.
(this is VB.NET, you have find the equivalent write-up for PHP)
Class Person
Public Property Name as String
Public Property Values() as Integer
End Class


Second solution would be: change second array into hashtable or dictionary with keys Person1, 2...and values from your second array. That way you can add/remove from the person as you wish.

Here is PHP primer[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900