duanhan9334 2018-04-08 17:41
浏览 35
已采纳

php从对象获取值[重复]

This question already has an answer here:

I've got basic array from my api:

{ "title": "offer title", "body": "offer body", 
"specialities": { "lang": "en", "id": "1", "icon": "0",
"name": "speciality name 1" }, "region": "region1" }

I want to get id value from request for my php variable lets say: $idVariable. How can I do it?

I tried something like:

$idVariable = $request->specialities[0]->id

but it seems not working. What is the right way?

Then how should I work with the arrays of object in this case:

{ "title": "offer title", "body": "offer body", 
"specialities": [
{ "lang": "en", "id": "1", "icon": "0", "name": "speciality name 1" },
 { "lang": "en", "id": "2", "icon": "0", "name": "speciality name 2" },
 { "lang": "en", "id": "2", "icon": "0", "name": "speciality name 3" },
 etc...], "region": "region1" }

To get id's of every object in specialities array? I know that it could be a duplicate question, but I ask for just a basic example.

I tried to use json decode like below:

json_decode($request->get('specialties'))->id

edit:

The almost-right way to do it is to decode json file first:

$data = json_decode($request);

and then get the right property from the array:

$id = $data['specialities'][0]['id'];

the problem now is that id is a string not an integer and by simply using:

$int_id = intval($id)

I've got $int_id = 0 instead of 1,2,3 etc

</div>
  • 写回答

1条回答 默认 最新

  • dtxs9017 2018-04-08 17:47
    关注

    You are getting a response from API in JSON you should use json_decode() and then use the data. Try this code.

    $json = '{ "title": "offer title", "body": "offer body", 
    "specialities": { "lang": "en", "id": "1", "icon": "0",
    "name": "speciality name 1" }, "region": "region1" }';
    
    $data = json_decode($json);
    echo $data->specialities->id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao