DS9
DS9

Reputation: 3033

Search into multidimensional array and change value of one key

I have one json request which contain multiple array:

{
  "user_type": "2",
  "user_id": "57",
  "client_detail": [
    {
      "server_user_id": "1",
      ........
      ........
      "is_active": "1",
      "client_local_id": "11"
    },
    {
      "server_user_id": "2",
      ........
      ........
      "is_active": "1",
      "client_local_id": "12"
    }
  ], 
  }

Using above request I change data into database. then return data from DB. but i have to pass client_local_id into response.

so suppose i got 3 result from DB then i have to return client_local_id(this field is not stored in DB, there is no need for that) with them. so i pass default client_local_id 0.

exa:

"client_detail": [
{
  "server_user_id": "1",
  ........
  ........
  "is_active": "1",
  "client_local_id": 0
},
{
  "server_user_id": "2",
  ........
  ........
  "is_active": "1",
  "client_local_id": 0
},
{
  "server_user_id": "3",
  ........
  ........
  "is_active": "1",
  "client_local_id": 0
},
]

then using below code i change value of client_local_id.

    $response = array('client_detail' => $dbvalue);
    /* Change Client Local ID */
    if(sizeof($client_detail_data)>0)
    {
        foreach($client_detail_data as $key=>$resclient_data)  // loop of request
        {
            foreach($response['client_detail'] as $key1=>$res_client)  //loop of response
            {
                //if id is match then change value
                if($res_client['server_user_id']==$resclient_data['server_user_id'])
                {
                    $response['client_detail'][$key1]['client_local_id'] = $resclient_data['client_local_id'];
                }
            }
        }
    }

But i think there is easy method, to do that. I have a multiple array in request so i don't want to use too much foreach loop. so how to solve it in proper way?

Thanks in advance.

Upvotes: 0

Views: 71

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

First of all let’s map server_user_ids to client_user_ids:

$s2c = array();
foreach($resclient_data as $item) {
  $s2c[$item['server_user_id']] = $item['client_user_id'];
}

Now we can use array_map directly on $response:

$response['client_detail'] = array_map(function($elem) use($s2c) {
  $elem['client_local_id'] = $s2c[$elem['server_local_id']];
  return $elem;
}, $response['client_detail']);

I diidn’t test the code, but hopefully the idea is clear.

Upvotes: 1

Related Questions