简体   繁体   中英

PHP - Adding element dynamically to each json object in array

I am using PHP for adding the JSON element to array.

This is my database table:

在此处输入图片说明

Here is my json array:

array:8 [

  0 => {#305
    +"Queue": "755"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
  1 => {#306
    +"Queue": "752"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
  2 => {#304
    +"Queue": "750"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
  }
]

Now I want to add callQueueName to every json object. Tried using put function as shown in below code but not getting added.

Here is my working code:

public static function getLoginAgentInfoTest(){
    $loginAgentInfo = 
      '[{"Queue":"755","Location":"427","MemberName":"PJSIP\/427","Status":"5"},
        {"Queue":"752","Location":"427","MemberName":"PJSIP\/427","Status":"5"},
        {"Queue":"750","Location":"427","MemberName":"PJSIP\/427","Status":"5"}]';

    $loginAgentInfo = json_decode($loginAgentInfo);
    
    $i = 0;
      
    foreach($loginAgentInfo[$i] as $loginData){ 
        
        $callQueueName = Tbcdrqueues::where('callqueue_no',$loginAgentInfo[$i]->Queue)->value('callqueue_name');
 
        $loginAgentInfo[$i].put('callQueueName',$callQueueName);
    
        $i++;
    }

    return $loginAgentInfo;
}

Expected output is:

array:8 [

  0 => {#305
    +"Queue": "755"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "New claims"
  }
  1 => {#306
    +"Queue": "752"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "Billing"
  }
  2 => {#304
    +"Queue": "750"
    +"Location": "427"
    +"MemberName": "PJSIP/427"
    +"Status": "5"
    +"callQueueName" : "Customer_Service"
  }
]

How can I achieve that ?

foreach($loginAgentInfo as $key => $loginData){ 
     $callQueueName = Tbcdrqueues::where('callqueue_no',$loginData->Queue)->value('callqueue_name');
     $loginAgentInfo[$key]->callQueueName = $callQueueName;
}

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