SwiftDeveloper SwiftDeveloper - 1 year ago 124
PHP Question

php sum selected keys in array with unique id

I have php array named

print_r($list)
you can see output under below;

Array (
[userid] => 1042
[picture] => 7a86b24.jpg
[share] => 6
[sharedate] => 2017-10-02 )

Array (
[userid] => 1042
[picture] => 7a86b24.jpg
[share] => 1
[sharedate] => 2017-10-02 )

Array (
[userid] => 1042
[picture] => 7a86b24.jpg
[share] => 56
[sharedate] => 2017-10-02 )

Array (
[userid] => 1007
[picture] => 3a83a6d.jpg
[share] => 136
[sharedate] => 2017-10-02 )

Array (
[userid] => 1007
[picture] => 3a83a6d.jpg
[share] => 18
[sharedate] => 2017-10-02 )

Array (
[userid] => 1007
[picture] => 3a83a6d.jpg
[share] => 5
[sharedate] => 2017-10-02 )


I want to sum share with userid equal ones. my array output must be under below.

Array (
[userid] => 1042
[picture] => 7a86b24.jpg
[share] => 63
[sharedate] => 2017-10-02 )

Array (
[userid] => 1007
[picture] => 3a83a6d.jpg
[share] => 159
[sharedate] => 2017-10-02 )


Also I want to use this array inside values with string like under below,

echo $userid;
echo $picture;
echo $share;
echo $sharedate;


How can I do it ? any idea. Thank you.

Answer Source

Here considering the date and picture are same for each userid.

 // define an empty array
 $new_array = array();
// loop the array
foreach($list as $value){
    $new_array[$value['userid']]['userid'] = $value['userid'];
    $new_array[$value['userid']]['picture'] = $value['picture'];
    // add the share values for each user
    $new_array[$value['userid']]['share'] = (isset($new_array[$value['userid']]['share'])) ? $new_array[$value['userid']]['share']+$value['share'] : $value['share'];
    $new_array[$value['userid']]['sharedate'] = $value['sharedate'];
}

print_r($new_array);

to reset the keys use array_values($new_array);

Out put:

Array
(
    [1042] => Array
        (
            [userid] => 1042
            [picture] => 7a86b24.jpg
            [share] => 63
            [sharedate] => 2017-10-02
        )

    [1007] => Array
        (
            [userid] => 1007
            [picture] => 3a83a6d.jpg
            [share] => 159
            [sharedate] => 2017-10-02
        )

)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download