Jump to content

SOLVED --- array_push() Using keys and values


JustinK101

Recommended Posts

Hello, I am trying to do something like this:

$myArray = array();
while(RESULTS)
{
    array_push($myArray, $row['first_name'] . ' ' . $row['last_name'] => $row['total']);
}

This doesnt appear to work though, seems you cant specify the key in the function call array_push() how is this possible? I need to use array push because I am doing this work inside a loop, and its not simply one addition, its an unknown number of additions to the array.

My Goal is have an array that look like:

Bob Smith => 23
Joe Blow => 34
Jane Doe => 34
etc, etc..
Link to comment
https://forums.phpfreaks.com/topic/29983-solved-array_push-using-keys-and-values/
Share on other sites

Ok, I am doing the following:

$myArrayKeys = array();
$myArrayValues = array();

while(RESULTS)
{
array_push($myArrayKeys, $row['first_name'] . ' ' . $row['last_name']);
array_push($myArrayValues, $row['total']);
}

$myArray = array_combine($myArrayKeys, $myArrayValues);

This almost works, except if there are duplicate keys it doesnt sum up the values, how can I do this?

Example:

Bob Smith => 24
Bob Smith => 45
Joe Smith => 23
Sue Smith => 12
Joe Smith => 10

Currently it displays:

Bob Smith => 45
Sue Smith => 12
Joe Smith => 10

How do I have it display

Bob Smith = > 69
Joe Smith => 33
Sue Smith => 12
I think you'll have to check to see if "Bob Smith" is already defined as a key in the array.  Then if he is, add the values.  If he's not "merge" him into the array (see my reply above).

To see if the key is part of the array:  http://www.php.net/manual/en/function.in-array.php

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.