0

I have these array in php:

[
    {
        "idespecialidad": "001",
        "especialidad": "ALBAÑIL",
        "cantidad": "3",
        "codpais": "PE"
    },
    {
        "idespecialidad": "006",
        "especialidad": "CHEF",
        "cantidad": "1",
        "codpais": "PE"
    },
    {
        "idespecialidad": "003",
        "especialidad": "ELECTRICISTA",
        "cantidad": "2",
        "codpais": "PE"
    },
    {
        "idespecialidad": "009",
        "especialidad": "PROGRAMADOR",
        "cantidad": "1",
        "codpais": "PE"
    }
]

And then i have the other array:

{
    "001": [
        {
            "idespecialidad": "001",
            "distancia": "2.3"
        },
        {
            "idespecialidad": "001",
            "distancia": "3.4"
        },
        {
            "idespecialidad": "001",
            "distancia": "10.0"
        }
    ],
    "006": [
        {
            "idespecialidad": "006",
            "distancia": "6.9"
        }
    ],
    "003": [
        {
            "idespecialidad": "003",
            "distancia": "8.3"
        },
        {
            "idespecialidad": "003",
            "distancia": "7.5"
        }
    ],
    "009": [
        {
            "idespecialidad": "009",
            "distancia": "7.3"
        }
    ]
}

What i need to do is get the distancia value (specifying: the min value) and set into the first array as a new key depending if it has the same idespecialidad.

Like this (harcoded):

[
    {
        "idespecialidad": "001",
        "especialidad": "ALBAÑIL",
        "cantidad": "3",
        "codpais": "PE",
        "distancia": "2.3"
    },
    {
        "idespecialidad": "006",
        "especialidad": "CHEF",
        "cantidad": "1",
        "codpais": "PE",
        "distancia": "6.9"
    },
    {
        "idespecialidad": "003",
        "especialidad": "ELECTRICISTA",
        "cantidad": "2",
        "codpais": "PE",
        "distancia": "7.5"
    },
    {
        "idespecialidad": "009",
        "especialidad": "PROGRAMADOR",
        "cantidad": "1",
        "codpais": "PE",
        "distancia": "7.3"
    }
]

1 Answer 1

1

Let $arr1 be your first array and $arr2 be your second

<?php

foreach ($arr1 as $i => $x) {
    $k = $x['idespecialidad'];
    $min = findmin($arr2, $k);
    $arr1[$i]['distancia'] = $min;
}

function findmin($data, $k)
{
    $min = $data[$k][0]['distancia'];
    for ($i = 1; $i < count($data[$k]); $i++) {
         if ($data[$k][$i]['distancia'] < $min) {
             $min = $data[$k][$i]['distancia'];
         }
    }
    return $min;
}
Sign up to request clarification or add additional context in comments.

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.