我正在尝试在php的for循环中使用带有键值对的array_push,但是在那里什么也没得到,我只得到2个没有值的键,谁能看到我在做什么错,< / p>
任何帮助将不胜感激。
$totalItems = $dataArray["totalItemsCount"];
$linkNamesTaken = array();
for($i=0; $i<$totalItems; $i++) {
array_push($linkNamesTaken[$dataArray["data"][$i]["subMediaType"]], $dataArray["data"][$i]["code"]);
}
print_r($linkNamesTaken);
我只得到
[Track] =>
[Album] =>
我期望类似
[Track] => LSD-ThundercloudswithSiaDiploLabrinth-Single
[Album] => DuaLipa-ElectricitywithDuaLipa-Album
dataArray包含如下数据
{"totalItemsCount": 7,
"data": [
{
"id": "366eff50-d6e2-4038-a091-4b84849c7e9e",
"url": "https://APItestboard.lnk.to/GeorgeEzra-Shotgun-Single",
"code": "GeorgeEzra-Shotgun-Single",
"subMediaType": "Track"
},
... 6 more items here like above
]
}
答案 0 :(得分:0)
也许您正在寻找类似的东西?
$totalItems = $dataArray["totalItemsCount"];
$linkNamesTaken = array();
foreach($totalItems as $key => $value) {
foreach($value['data'] as $key2 => $value2) {
$linkNamesTaken[]['subMediaType'] = $value2['subMediaType'];
$linkNamesTaken[]['code'] = $value2['code'];
}
}
答案 1 :(得分:0)
在这里,您的subMediaType
数组中的键具有code
和值为linkNamesTaken
的键
$linkNamesTaken = array();
foreach($dataArray['data'] as $k1 => $v1) { //7 loop on key value pair
$linkNamesTaken[$v1['subMediaType']] = $v1['code']; // hopefully key value should be unique.
}
print_r($linkNamesTaken);
O / P
Array
(
[Track] => GeorgeEzra-Shotgun-Single
[New Track] => GeorgeEzra-Shotgun-Double
)
编辑:请参见http://php.net/manual/en/function.array-push.php#108118