PHP JSON特定的数组键

时间:2017-08-06 11:43:33

标签: php arrays json

我正在尝试将chooseId带回来并将它们放在我的json响应中的数组中,但我无法管理它。我的json响应为

[
{
marketId: "1.133102670",
marketName: "2m Hrd",
totalMatched: 39556.86,
runners: [
{
selectionId: 13764229,
runnerName: "Kereman",
handicap: 0,
sortPriority: 1
},
{
selectionId: 11378898,
runnerName: "City Dreamer",
handicap: 0,
sortPriority: 2
},
{
selectionId: 12279462,
runnerName: "Costa Percy",
handicap: 0,
sortPriority: 3
},
{
selectionId: 11316530,
runnerName: "Platos Kode",
handicap: 0,
sortPriority: 4
},
{
selectionId: 11177700,
runnerName: "Parkwarden",
handicap: 0,
sortPriority: 5
}
]
},
{
marketId: "1.133102480",
marketName: "7f Nov Stks",
totalMatched: 23164.32,
runners: [
{
selectionId: 13428423,
runnerName: "Delph Crescent",
handicap: 0,
sortPriority: 1
},
{
selectionId: 13079071,
runnerName: "Red Force One",
handicap: 0,
sortPriority: 2
},
{
selectionId: 13372659,
runnerName: "Porth Swtan",
handicap: 0,
sortPriority: 3
},
{
selectionId: 12943079,
runnerName: "Zoffalee",
handicap: 0,
sortPriority: 4
},
{
selectionId: 13373353,
runnerName: "Snooker Jim",
handicap: 0,
sortPriority: 5
},
{
selectionId: 13763129,
runnerName: "Lineofintelligence",
handicap: 0,
sortPriority: 6
},
{
selectionId: 13437954,
runnerName: "Surrender",
handicap: 0,
sortPriority: 7
},
{
selectionId: 13605452,
runnerName: "Cum Spiro Spero",
handicap: 0,
sortPriority: 8
}
]
}

我的代码如下所示:

$arr = json_decode($jsonResponse, true);
echo $arr['runners'][0]['selectionId'];

我出错的任何想法,甚至我如何解决这个问题,以便将所有选择ID带回一个阵列。

提前感谢您提供任何帮助或建议。

3 个答案:

答案 0 :(得分:0)

你必须循环抛出所有runners元素,然后将它们聚合在另一个数组中。

$selectionIds =  array();
for($i=0; $i<count($arr['runners']) ; $i++)
{
array_push($selectionIds, $arr[0]['runners'][$i]->selectionId);
}
var_dump($selectionIds);

答案 1 :(得分:0)

应为$arr[0]['runners'][0]['selectionId']

答案 2 :(得分:0)

只需使用这样的php函数array_column()

  

数组array_column(数组$ input,混合$ column_key [,混合   $ index_key = null])

     

array_column()返回输入的单个列的值,   由column_key标识。

     

输入:从中提取一列值的多维数组或对象数组。

     

column_key :要返回的值列。此值可以是您要检索的列的整数键,也可以是关联数组或属性名称的字符串键名。

$arr = json_decode($jsonResponse, true);
$selectionIds = array_column($records, 'selectionId');