在php中映射动态变量

时间:2018-04-12 13:14:52

标签: php rest

如何从REST api调用中为元素赋值?

假设我在api通话4中有echo $resultArray[0]['number'][0]['value'];的结果。然后我想为该结果分配相应的值,所以每当我发出下一个调用时,我都会得到House作为结果。

Assigning string values:
    4 = House
    5 = Bedroom

更新:

[{"number":[{"value":4}],"uuid":[{"value":"123-123-123-123-123"}],"vid":[{"value":123}],"langcode":[{"value":"en"}],"type":[{"target_id":"test","target_type":"test_type","target_uuid":"456-456-456-456-456"}],"revision_timestamp":[{"value":123345678}],"revision_uid":[{"target_id":1,"target_type":"user","target_uuid":"321-321-321-321-321","url":"\/user\/1\/stream"}],"revision_log":[],"status":[{"value":false}],"title":[{"value":"John Test Patch"}]}]

3 个答案:

答案 0 :(得分:0)

维护一个关联数组,用于存储sting和value。 匹配关联数组中的结果以显示所需的值。



    $mapArray = array('4'=>'home','5'=>'office');
    $response_decoded=json_decode($response,true); //$response is json from api call.
    if(isset($mapArray[$response_decoded['number']['0']['value']])
    {
        $response_decoded['number']['0']['value']=$mapArray[$response_decoded['number']['0']['value']];
}
    else
    {
        echo "value not present in array";
    }
 

答案 1 :(得分:0)

让我们假设你已经将这个$ resultArray解码为你的api的响应,用php保存,试试这个:

if(!empty($resultArray)){
foreach($resultArray as $key => $object){
    if($object->number[0]->value ==4){
        $object->number[0]->value= "house";
    }
    else if($object->number[0]->value ==5){
      $object->number[0]->value= "Bedroom";
    }
     // if you have another use case  add them after here 
    /* else if(){
     }
     .
     .
     else(){
     }
     */
}
}

答案 2 :(得分:0)

$var = $resultArray[0]['number'][0]['value'];
switch($var){
 case 0:
  $varString = "text"; 
  break;

case 4: 
 $varString = "House";
 break;

case default:
 $varString = "not 0 or 4"; 
 break; 
}

那应该为你做诀窍:)