[英]how to use array_push with key value in a for loop in php
I'm trying to use array_push with key value pair in a for loop in php but I'm not getting anything in there, I only get 2 keys with no values, can anyone see what I'm doing wrong, 我正在尝试在php的for循环中使用带有键值对的array_push,但是在那里什么也没得到,我只得到2个没有值的键,谁能看到我在做什么错,
any help would be appreciated. 任何帮助,将不胜感激。
$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);
I'm only getting 我只会
[Track] =>
[Album] =>
I'm expecting something like 我期待类似的东西
[Track] => LSD-ThundercloudswithSiaDiploLabrinth-Single
[Album] => DuaLipa-ElectricitywithDuaLipa-Album
the dataArray contains data like the following 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
]
}
Maybe you're looking for something like this? 也许您正在寻找这样的东西?
$totalItems = $dataArray["totalItemsCount"];
$linkNamesTaken = array();
foreach($totalItems as $key => $value) {
foreach($value['data'] as $key2 => $value2) {
$linkNamesTaken[]['subMediaType'] = $value2['subMediaType'];
$linkNamesTaken[]['code'] = $value2['code'];
}
}
Here you go with key has subMediaType
& value as code
in your linkNamesTaken
array 在这里,您在linkNamesTaken
数组中使用键将subMediaType
和值作为code
$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 O / P
Array
(
[Track] => GeorgeEzra-Shotgun-Single
[New Track] => GeorgeEzra-Shotgun-Double
)
EDIT : see http://php.net/manual/en/function.array-push.php#108118 编辑 :请参阅http://php.net/manual/zh/function.array-push.php#108118
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.