简体   繁体   中英

According to the values within the array key value in php

I have multiple arrays like this:

$value1 = array ("10" => "car", "20" => "home", "30" => "ball");
$value2 = array ("50" => "car", "60" => "home", "70" => "ball");
$value3 = array ("100" => "car", "110" => "home", "120" => "ball");

Now I want to merge those arrays by the value and while merging adding the key values together.

Pseudo code:

$endvalue = $value1 + $value2 + $value3;

print_r ($endvalue);

Expected output:

"160" => "car"
"190" => "home"
"220" => "ball"

I have a database like this;

name    facebookCount   tweetCount   googleCount

 car    20              50           100
home    50              60           10
ball    30              10           70

.. and I want to find the most shared value..

Like;

car (20 + 50 + 100)

home (50+ 60 + 10)

ball (30 + 10 + 70)

..and list

car > home > ball

Can you help me ?

The solution for input arrays with non-duplicate keys using array_values , array_combine and array_search functions:

...
$arrList = [$value1, $value2, $value3];  // wrapping input arrays with outer array
$names = array_combine(array_values($value1), array_fill(0, count($arrList), 0));  // getting base names list

foreach ($names as $k => &$num) {
    foreach ($arrList as $arr) {
        $num += (int) array_search($k, $arr);
    }
}

print_r($names);

I believe that the final array should be an associative array, cause there could be cases when the total sums will be the same among grouped names

The output:

Array
(
    [car] => 160
    [home] => 190
    [ball] => 220
)

An SQL solution would probably be faster in your case, and it is in fact very simple. Simple arithmetic is no problem for SQL.

Consider a table with the following structure:

CREATE TABLE `social` (
  `name` varchar(50) NOT NULL,
  `facebook` int(11) NOT NULL,
  `twitter` int(11) NOT NULL,
  `google` int(11) NOT NULL,
  PRIMARY KEY (`name`)
);

Then this query:

SELECT name, (facebook + twitter + google) as shares FROM social
ORDER BY shares DESC

Gives you the following result:

name    shares
car     170
home    120
ball    110

Not much to explain I guess, but feel free to ask if anything is unclear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM