[英]Push a set of values to an array based on another unique value in the same array
[英]Set a variable using an array value based on another value in the same array
我是新來的。
我有一種情況,我需要遍歷一個數組,確定該數組中的$key
的值是否為1
,然后使用來自同一數組中不同$key
的$value
設置一個變量。
這就是我的意思。
我從 API 中檢索 JSON 數組,該數組部分看起來像這樣:
(
[6] => Array
(
[element] => 191
[position] => 7
[multiplier] => 2
[is_captain] => 1
[is_vice_captain] =>
)
[7] => Array
(
[element] => 171
[position] => 8
[multiplier] => 1
[is_captain] =>
[is_vice_captain] =>
)
我想要做的是遍歷數組,確定鍵[is_captain]
是否具有值 (1),並使用來自不同$key
的值設置變量,特別是[element]
。
例如,在上面的代碼[6]
中,如果[is_captain]
的值為1
,我想創建一個值為[element] => 191
(191) 的變量。
這是我留下東西的地方:
for($i = 0; $i < count($players['picks']); $i++){
foreach ($fpl_team_picks['picks'][$keys[$i]] as $key => $value){
if (isset($key['is_captain'])){
$variable = $value['element'];
}
}
}
它不起作用。 我已經嘗試過isset
function 和一系列數組函數( array_column
等),但我很難過。
$arr = array(
6 => array(
'element' => 191,
'position' => 7,
'multiplier' => 2,
'is_captain' => 1,
'is_vice_captain' => null
),
7 => array(
'element' => 171,
'position' => 8,
'multiplier' => 1,
'is_captain' => null,
'is_vice_captain' => null
)
);
在數組上設置 foreach 循環,設置值,遍歷值,找到鍵值$index === 'is_captain'
並確保它設置為1
-> $data === '1'
。 如果這是真的定義你的變量。
foreach($arr as $value){
foreach($value as $index => $data){
if($index === 'is_captain' && $data === 1){
$element = $value['element'];
echo $element; // $element now holds the value where key = `element` if 'is_captain' is equal to `1`
}
}
}
在您的代碼中,將$key['is_captain']
更改為$key === 'is_captain'
然后在相同條件下查找它的值是否匹配。
如果鍵等於目標鍵is_captain
並且鍵值等於1
,則將鍵集的值設置為element
並將其分配給您的變量:
if ($key === 'is_captain' && $val === 1)){
$variable = $value['element'];
}
我的方向是正確的,非常感謝貢獻者的幫助。
我最初的問題並沒有明確說明我正在使用嵌套數組。 我的數組片段沒有顯示。 我學到了關於完整性的教訓。 (我是新來的)。
一旦我編寫了處理嵌套數組的代碼塊並稍微修改了條件,我就成功了。 這是有效的最終代碼:
$x = 0;
$captainsArr = array($fpl_team_picks['picks']);
foreach($captainsArr[$x++] as $value) {
if (is_array($value)){
foreach ($value as $index => $data) {
if ($index === 'is_captain' && $data == 1){
$captain = $value['element'];
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.