Bulk friend Request insertion based on array input in php

57
February 11, 2019, at 07:40 AM

I have an array,

Array (
    [0] => Array ( [did] => 12 [uid] => 21 )
    [1] => Array ( [did] => 10 [uid] => 12 )
    [2] => Array ( [did] => 9 [uid] => 11 )
    [3] => Array ( [did] => 10 [uid] => 11 )
    [4] => Array ( [did] => 12 [uid] => 11 ) 
)

where I want all the uids who have the same did value to be connected with each other. For example- for did=12, uids- 21 & 11 should be connected with each other. I am struggling to figure out how to do this in PHP and MySQL? Please note that array gets generated dynamically using query and can have many rows.

Answer 1

You could loop over the array and use the did as the key. If the key already exists, add to the array, else create a new entry using the key:

$items = [
    ["did" => 12, "uuid" => 21],
    ["did" => 10, "uuid" => 12],
    ["did" => 9, "uuid" => 11],
    ["did" => 10, "uuid" => 11],
    ["did" => 12, "uuid" => 11],
];
$result = [];
foreach ($items as $i) {
    array_key_exists($i["did"], $result) ? $result[$i["did"]][] = $i["uuid"] : $result[$i["did"]] = [$i["uuid"]];
}
print_r($result);

Result:

Array
(
    [12] => Array
        (
            [0] => 21
            [1] => 11
        )
    [10] => Array
        (
            [0] => 12
            [1] => 11
        )
    [9] => Array
        (
            [0] => 11
        )
)

Php demo

READ ALSO
Using an auto_increment sequence for cursor purpose in mysql ? Any other Alternative?

Using an auto_increment sequence for cursor purpose in mysql ? Any other Alternative?

I m creating a application where there are users and posts, and user can likes posts, so i have created a table ,

35
MySQL - Using COALESCE with DATE_ADD and DATE_SUB to get next/previous record

MySQL - Using COALESCE with DATE_ADD and DATE_SUB to get next/previous record

I am trying to query MySQL to select the previous and next recordI need help in using COALESCE and DATE_ADD/DATE_SUB together

54
How to upgrade MySQL database schema in respective to sprint releases?

How to upgrade MySQL database schema in respective to sprint releases?

let say we have a Qt/qml based desktop application, this is using mysql as local db

47
Grant MySQL permissions on current database?

Grant MySQL permissions on current database?

I can grant permissions with a static database name in the GRANT statement

37