0
    <?php
$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png"
    ]
];

$userProductsData = [
    [
    "UPID" => "5f10482574d83d4b6fe007",
    "UID" => "5f10482574d83d4b726fe5",
    ]
];
$userDetailsResult = [];
foreach ($userData as $key => $value) {
    $userData[$key]["UPID"] = $userProductsData[$value["UID"]] ?? [];
}

Expected Output

$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png",
        "UPID" => "5f10482574d83d4b6fe007"
    ]
];

i have two aray UID common for both array, now i want to take UPID from $userProductsData and push into $userData, i have tried not working properly, kindly anyone update my code please ?>

3
  • $userProductsData[$value["UID"]] becomes $userProductsData['5f10482574d83d4b726fe5'], and there is no element by that key in that array. Commented Aug 27, 2020 at 7:23
  • loop each $userProductsData, then inside loop each $userData, then use an if Commented Aug 27, 2020 at 7:26
  • Why $userDetailsResult = []; ? Commented Aug 27, 2020 at 8:06

2 Answers 2

1

Try this one.


$userData = [
    [
        "UID" => "5f10482574d83d4b726fe5",
        "name" => "Yug Gill",
        "orgID" => "5f10481d74d83d4b726",
        "imageURL" => "female.png"
    ]
];

$userProductsData = [
    [
    "UPID" => "5f10482574d83d4b6fe007",
    "UID" => "5f10482574d83d4b726fe5",
    ]
];
$userDetailsResult = [];

foreach ($userProductsData as $key => $value) {
    $userData[$key]["UPID"] = $value['UPID'];
   
}

print_r($userData);

Sign up to request clarification or add additional context in comments.

2 Comments

single loop we cannot achieve this ?
What do you mean by single loop? It is because of the 2 foreach loops? If that's the case, you can actually remove the first foreach loop.
0

Your $userProductsData is a regular array, it has indexes 0, 1, 2 etc... Then you are trying to get an item from this array by string key "5f10482574d83d4b726fe5".

$userProductsData should be a key array like that:

$userProductsData = [
    "5f10482574d83d4b726fe5" => [
        "UPID" => "5f10482574d83d4b6fe007",
        "UID" => "5f10482574d83d4b726fe5",
    ],
];

Then you can get an item from this array by key "5f10482574d83d4b726fe5".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.