Retrieve all values of a key name from PHP Multidimensional array

I have a multidimensional array provided by an outside source, and I would like to pull all of the values from a certain key name. This key will exist in several arrays within this array.
There will be 9 or 10 results off of this, and I need to add the values together.
I am not sure how to search the array for these keys, as I am new to PHP.

Below is an example
print_r

Open in new window

of part of the array.
I am trying to retrieve only the
numDeaths

Open in new window

values. I need to get those, then add them together.
If they were put into another array, I could use
array_sum

Open in new window

.

Array ( [userId] => 21401054 [events] => Array ( [0] => Array ( [eventId] => 1857605688 [invalid] => [eventMode] => CLASSIC [eventType] => MATCHED_event [subType] => NORMAL [mapId] => 11 [teamId] => 200 [playerId] => 105 [casting1] => 4 [casting2] => 12 [level] => 30 [amountEarned] => 101 [createDate] => 1434424803588 [fellowPlayers] => Array ( [0] => Array ( [userId] => 50695442 [teamId] => 100 [playerId] => 133 ) [1] => Array ( [userId] => 48184422 [teamId] => 100 [playerId] => 245 ) [2] => Array ( [userId] => 42839142 [teamId] => 200 [playerId] => 84 ) [3] => Array ( [userId] => 40292608 [teamId] => 200 [playerId] => 157 ) [4] => Array ( [userId] => 49899936 [teamId] => 100 [playerId] => 113 ) [5] => Array ( [userId] => 31152132 [teamId] => 200 [playerId] => 54 ) [6] => Array ( [userId] => 49959901 [teamId] => 100 [playerId] => 111 ) [7] => Array ( [userId] => 23179063 [teamId] => 200 [playerId] => 31 ) [8] => Array ( [userId] => 45090515 [teamId] => 100 [playerId] => 22 ) ) [stats] => Array ( [level] => 16 [goldEarned] => 8896 [numDeaths] => 4 [barracksdestroyed] => 1 [turretsdestroyed] => 2 [buildingsdestroyed] => 88 [playersdestroyed] => 2 [goldSpent] => 8148 [totalDealt] => 60062 [totalTaken] => 17870 [team] => 200 [win] => 1 [neutralbuildingsdestroyed] => 2 [largestMultidestroy] => 1 [physicalDealtPlayer] => 39479 [forceDealtPlayer] => 20582 [physicalTaken] => 9909 [forceTaken] => 7067 [largestCriticalStrike] => 354 [timePlayed] => 2168 [totalHeal] => 433 [totalUnitsHealed] => 1 [assists] => 6 [item0] => 1055 [item1] => 2003 [item2] => 3158 [item3] => 3078 [item4] => 3110 [item6] => 3340 [visiontrinksBought] => 1 [forceDealtToplayers] => 3369 [physicalDealtToplayers] => 2185 [totalDealtToplayers] => 5555 [trueTaken] => 893 [trinkdestroyed] => 1 [trinkPlaced] => 8 [neutralbuildingsdestroyedEnemyBase] => 2 [totalTimeCrowdControlDealt] => 738 [playerRole] => 4 [playerPosition] => 1 ) ) [1] => Array ( [eventId] => 1857605688 [invalid] => [eventMode] => CLASSIC [eventType] => MATCHED_event [subType] => NORMAL [mapId] => 11 [teamId] => 200 [playerId] => 105 [casting1] => 4 [casting2] => 12 [level] => 30 [amountEarned] => 101 [createDate] => 1434424803588 [fellowPlayers] => Array ( [0] => Array ( [userId] => 50695442 [teamId] => 100 [playerId] => 133 ) [1] => Array ( [userId] => 48184422 [teamId] => 100 [playerId] => 245 ) [2] => Array ( [userId] => 42839142 [teamId] => 200 [playerId] => 84 ) [3] => Array ( [userId] => 40292608 [teamId] => 200 [playerId] => 157 ) [4] => Array ( [userId] => 49899936 [teamId] => 100 [playerId] => 113 ) [5] => Array ( [userId] => 31152132 [teamId] => 200 [playerId] => 54 ) [6] => Array ( [userId] => 49959901 [teamId] => 100 [playerId] => 111 ) [7] => Array ( [userId] => 23179063 [teamId] => 200 [playerId] => 31 ) [8] => Array ( [userId] => 45090515 [teamId] => 100 [playerId] => 22 ) ) [stats] => Array ( [level] => 16 [goldEarned] => 8896 [numDeaths] => 4 [barracksdestroyed] => 1 [turretsdestroyed] => 2 [buildingsdestroyed] => 88 [playersdestroyed] => 2 [goldSpent] => 8148 [totalDealt] => 60062 [totalTaken] => 17870 [team] => 200 [win] => 1 [neutralbuildingsdestroyed] => 2 [largestMultidestroy] => 1 [physicalDealtPlayer] => 39479 [forceDealtPlayer] => 20582 [physicalTaken] => 9909 [forceTaken] => 7067 [largestCriticalStrike] => 354 [timePlayed] => 2168 [totalHeal] => 433 [totalUnitsHealed] => 1 [assists] => 6 [item0] => 1055 [item1] => 2003 [item2] => 3158 [item3] => 3078 [item4] => 3110 [item6] => 3340 [visiontrinksBought] => 1 [forceDealtToplayers] => 3369 [physicalDealtToplayers] => 2185 [totalDealtToplayers] => 5555 [trueTaken] => 893 [trinkdestroyed] => 1 [trinkPlaced] => 8 [neutralbuildingsdestroyedEnemyBase] => 2 [totalTimeCrowdControlDealt] => 738 [playerRole] => 4 [playerPosition] => 1 ) ) 

Open in new window


Thanks in advance for the help!
zerowizardAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
Probably a good application for this function:
http://php.net/manual/en/function.array-walk-recursive.php

I'll see if  can put together an example from the information in the question.
Ray PaseurCommented:
I'm not usually a big fan of using global variables, but it's an expedient that seems to work out well here.
http://iconoun.com/demo/temp_zerowizard.php
<?php // demo/temp_zerowizard.php
/**
 * SEE: http://www.experts-exchange.com/questions/28689831/Retrieve-all-values-of-a-key-name-from-PHP-Multidimensional-array.html
 * REF: http://php.net/manual/en/function.array-walk-recursive.php
 */
error_reporting(E_ALL);
echo '<pre>';

// REDACTRED FROM THE POST AT E-E
$testdata =
Array
( 'userId' => 21401054
, 'events' => Array
  ( '0' => Array
    ( 'eventId' => 1857605688
    , 'fellowPlayers' => Array
      ( '0' => Array ( 'userId' => 50695442, 'teamId' => 100, 'playerId' => 133 )
      , '1' => Array ( 'userId' => 48184422, 'teamId' => 100, 'playerId' => 245 )
      )
    , 'stats' => Array
      ( 'level' => 16
      , 'goldEarned' => 8896
      , 'numDeaths' => 4
      , 'barracksdestroyed' => 1
      )
    )
   , '1' => Array
    ( 'eventId' => 1857605688
    , 'fellowPlayers' => Array
      ( '0' => Array ( 'userId' => 50695442, 'teamId' => 100, 'playerId' => 133 )
      , '1' => Array ( 'userId' => 48184422, 'teamId' => 100, 'playerId' => 245 )
      )
    , 'stats' => Array
      ( 'level' => 16
      , 'goldEarned' => 8896
      , 'numDeaths' => 4
      , 'barracksdestroyed' => 1
      )
    )
  )
)
;

// DOES IT LOOK RIGHT?  YES
// var_dump($testdata);

// THE CALLBACK
function find_num_deaths($item, $key)
{
    global $numDeaths;
    if ($key != 'numDeaths') return;
    $numDeaths += $item;
}

// LOCATE THE DATA
$numDeaths = 0;
array_walk_recursive($testdata, 'find_num_deaths');
var_dump($numDeaths);

Open in new window

Ray PaseurCommented:
Final note, if you're new to PHP and want to learn the language, this article can help steer you to good learning resources, and away from the many bad examples that litter the internet!
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

zerowizardAuthor Commented:
Hmmm. When I try to use the function and array_walk_recursive on my full array, it gives an error.

array_walk_recursive() expects parameter 1 to be array, null given in ...
On this line: array_walk_recursive($data, 'find_num_deaths');

I was not using the array you created, as I see it works based on your example. I wonder if it could be a formatting issue?

The array I am using comes from a curl using a JSON api.

$myArray = json_decode($api_recent, true);

Open in new window

In my case, I am using your example on $myArray.
zerowizardAuthor Commented:
I wonder if it would be easier to just parse what I need from the JSON content. Essentially, it is the same, but the examples I read online had them putting it into an array.
zerowizardAuthor Commented:
I have removed the 'true' option from my json_decode, and it looks to be formatted more similarly to your example.

stdClass Object
(
    [userId] => 21401054
    [games] => Array
        (
            [0] => stdClass Object
                (
                    [gameId] => 1857605688
                    [invalid] => 
                    [gameMode] => CLASSIC
                    [gameType] => MATCHED_GAME
                    [subType] => NORMAL
                    [mapId] => 11
                    [teamId] => 200
                    [playerId] => 105
                    [spell1] => 4
                    [spell2] => 12
                    [level] => 30
                    [amountEarned] => 101
                    [createDate] => 1434424803588
                    [fellowPlayers] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [userId] => 50695442
                                    [teamId] => 100
                                    [playerId] => 133
                                )

                            [1] => stdClass Object
                                (
                                    [userId] => 48184422
                                    [teamId] => 100
                                    [playerId] => 245
                                )

                            [2] => stdClass Object
                                (
                                    [userId] => 42839142
                                    [teamId] => 200
                                    [playerId] => 84
                                )

                            [3] => stdClass Object
                                (
                                    [userId] => 40292608
                                    [teamId] => 200
                                    [playerId] => 157
                                )

                            [4] => stdClass Object
                                (
                                    [userId] => 49899936
                                    [teamId] => 100
                                    [playerId] => 113
                                )

                            [5] => stdClass Object
                                (
                                    [userId] => 31152132
                                    [teamId] => 200
                                    [playerId] => 54
                                )

                            [6] => stdClass Object
                                (
                                    [userId] => 49959901
                                    [teamId] => 100
                                    [playerId] => 111
                                )

                            [7] => stdClass Object
                                (
                                    [userId] => 23179063
                                    [teamId] => 200
                                    [playerId] => 31
                                )

                            [8] => stdClass Object
                                (
                                    [userId] => 45090515
                                    [teamId] => 100
                                    [playerId] => 22
                                )

                        )

                    [stats] => stdClass Object
                        (
                            [level] => 16
                            [goldEarned] => 8896
                            [numDeaths] => 4
                            [basesDestroyed] => 1
                            [turretsDestroyed] => 2
                            [minionsDestroyed] => 88
                            [playersDestroyed] => 2
                            [goldSpent] => 8148
                            [totalDamageDealt] => 60062
                            [totalDamageTaken] => 17870
                            [team] => 200
                            [win] => 1
                            [neutralMinionsDestroyed] => 2
                            [largestMultiKill] => 1
                            [physicalDamageDealtPlayer] => 39479
                            [sliceDamageDealtPlayer] => 20582
                            [physicalDamageTaken] => 9909
                            [sliceDamageTaken] => 7067
                            [largestCriticalStrike] => 354
                            [timePlayed] => 2168
                            [totalHeal] => 433
                            [totalUnitsHealed] => 1
                            [assists] => 6
                            [item0] => 1055
                            [item1] => 2003
                            [item2] => 3158
                            [item3] => 3078
                            [item4] => 3110
                            [item6] => 3340
                            [sighttotesBought] => 1
                            [sliceDamageDealtToplayers] => 3369
                            [physicalDamageDealtToplayers] => 2185
                            [totalDamageDealtToplayers] => 5555
                            [trueDamageTaken] => 893
                            [toteDestroyed] => 1
                            [totePlaced] => 8
                            [neutralMinionsDestroyedEnemyJungle] => 2
                            [totalTimeCrowdControlDealt] => 738
                            [playerRole] => 4
                            [playerPosition] => 1
                        )

                )

            [1] => stdClass Object
                (
                    [gameId] => 1857589889
                    [invalid] => 
                    [gameMode] => CLASSIC
                    [gameType] => MATCHED_GAME
                    [subType] => NORMAL
                    [mapId] => 11
                    [teamId] => 200
                    [playerId] => 105
                    [spell1] => 4
                    [spell2] => 12
                    [level] => 30
                    [amountEarned] => 101
                    [createDate] => 1434422323158
                    [fellowPlayers] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [userId] => 26326852
                                    [teamId] => 100
                                    [playerId] => 19
                                )

                            [1] => stdClass Object
                                (
                                    [userId] => 42839142
                                    [teamId] => 200
                                    [playerId] => 35
                                )

                            [2] => stdClass Object
                                (
                                    [userId] => 21514417
                                    [teamId] => 200
                                    [playerId] => 429
                                )

                            [3] => stdClass Object
                                (
                                    [userId] => 23179063
                                    [teamId] => 200
                                    [playerId] => 31
                                )

                            [4] => stdClass Object
                                (
                                    [userId] => 19858528
                                    [teamId] => 200
                                    [playerId] => 245
                                )

                            [5] => stdClass Object
                                (
                                    [userId] => 24137530
                                    [teamId] => 100
                                    [playerId] => 29
                                )

                            [6] => stdClass Object
                                (
                                    [userId] => 28382525
                                    [teamId] => 100
                                    [playerId] => 59
                                )

                            [7] => stdClass Object
                                (
                                    [userId] => 37447016
                                    [teamId] => 100
                                    [playerId] => 432
                                )

                            [8] => stdClass Object
                                (
                                    [userId] => 38869545
                                    [teamId] => 100
                                    [playerId] => 34
                                )

                        )

                    [stats] => stdClass Object
                        (
                            [level] => 15
                            [goldEarned] => 9019
                            [numDeaths] => 4
                            [turretsDestroyed] => 2
                            [minionsDestroyed] => 117
                            [playersDestroyed] => 1
                            [goldSpent] => 8233
                            [totalDamageDealt] => 64445
                            [totalDamageTaken] => 13113
                            [team] => 200
                            [win] => 1
                            [neutralMinionsDestroyed] => 1
                            [largestMultiKill] => 1
                            [physicalDamageDealtPlayer] => 45489
                            [sliceDamageDealtPlayer] => 18955
                            [physicalDamageTaken] => 8114
                            [sliceDamageTaken] => 3525
                            [timePlayed] => 2182
                            [totalHeal] => 209
                            [totalUnitsHealed] => 1
                            [assists] => 6
                            [item0] => 1055
                            [item1] => 2003
                            [item2] => 3110
                            [item3] => 3158
                            [item4] => 3078
                            [item5] => 1036
                            [item6] => 3340
                            [sliceDamageDealtToplayers] => 2821
                            [physicalDamageDealtToplayers] => 2615
                            [totalDamageDealtToplayers] => 5436
                            [trueDamageTaken] => 1474
                            [totePlaced] => 7
                            [neutralMinionsDestroyedEnemyJungle] => 1
                            [totalTimeCrowdControlDealt] => 1735
                            [playerRole] => 4
                            [playerPosition] => 1
                        )

                )

        )

)

Open in new window

Slick812Commented:
greetings, If I were dealing with the output from a HTML service for game stats, as you show here, Then of primary importance for me to know to get specific info-data, and in your case unravel the returned object and xtract the needed elements, , , is I would need to be VERY SURE of the returned data having the same format of array-object names (properties) and array numbers each time the data is returned,  I will just take for granted that the structure and format does not change for a different request form the service..

As I see your Object structure the info-data you seek for the number of deaths in a game is here -
   $myObject = json_decode($api_recent);
   $numDeaths = $myObject->games[0]->stats->numDeaths;
in the games Array, the "stats"  property, and the numDeaths property of that "stats"  object.

so you may can use code like this -
$total = 0;
$myObject = json_decode($api_recent);

for($i = 0; $i < count($myObject->games); ++$i) {
$total += $myObject->games[$i]->stats->numDeaths;
}

echo 'This is the Total of deaths in all games recorded : '.$total;

Open in new window


But maybe there may be other factors which I do not factor in here? ?

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
zerowizardAuthor Commented:
Awesome! That does exactly what I need! I should be able to modify this to fit exactly what I'm trying to do!
Slick812Commented:
you can get any of the other game stats by just changing the property name -
    $tGold += $myObject->games[$i]->stats->goldEarned;
    $tDamage += $myObject->games[$i]->stats->totalDamageDealt;
Ray PaseurCommented:
The array I am using comes from a curl using a JSON api.
"Little details" like that matter.  If you want to post the actual JSON string, instead of some variant of it, I'll be glad to show you how to work with a JSON response!
Ray PaseurCommented:
When you get a message like this...
array_walk_recursive() expects parameter 1 to be array, null given in ...
... the right thing to do is examine the contents of the $data variable, which is the return value from the API.  PHP says it's NULL, which would lead me to believe that the JSON API failed.  There are ways to use cURL that will enable you to see and handle the inevitable errors that come up when you use external APIs, but that is a topic for another question.  For now the best thing would be to see the JSON string.
zerowizardAuthor Commented:
Excellent work guys! I appreciate the quick responses and helpful information!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.