使用foreach循环创建PHP函数

时间:2017-05-30 20:57:58

标签: php function foreach

我有一个foreach循环什么工作正常但我需要在同一页面中调用它几次以获得不同的结果所以我认为一个函数会更好但我会继续Warning: Invalid argument supplied for foreach()

继承了有效的代码

$weaponSlot = '1';

$talentGridHash =  $json2['Response']['data']['buckets']['Equippable'][''.$weaponSlot.'']['items']['0']['talentGridHash'];

$nodes = $json2['Response']['data']['buckets']['Equippable'][''.$weaponSlot.'']['items']['0']['nodes'];

foreach($nodes as $talentNode) {
// Perform operations on each nodes...

if($talentNode['isActivated'] && $talentNode['state'] === 10){
      $nodesActive[] = $talentNode;

    $perkName = $json2['Response']['definitions']['talentGrids'][''.$talentGridHash.'']['nodes'][''.$talentNode['nodeHash'].'']['steps']['0']['nodeStepName'];
    $perkIcon =  $json2['Response']['definitions']['talentGrids'][''.$talentGridHash.'']['nodes'][''.$talentNode['nodeHash'].'']['steps']['0']['icon'];

    if (strpos($perkName, 'Damage') == false) { 

$perkOutput .= '<div style="border:1px solid #999; border-radius:3px; padding:1px; float:left; margin-right:8px"><img src="http://www.example.com'.$perkIcon.'" height="22" title='.$perkName.'" /></div>'; 


    }

}

}

echo $perkOutput;

将代码转换为函数...我错过了什么? (顺便说一句,这是我第一次完成一项功能,在线查看示例)

$perkOutput = null;
function getItemPerks($weaponSlot){

$talentGridHash =  $json2['Response']['data']['buckets']['Equippable'][''.$weaponSlot.'']['items']['0']['talentGridHash'];

$nodes = $json2['Response']['data']['buckets']['Equippable'][''.$weaponSlot.'']['items']['0']['nodes'];

foreach($nodes as $talentNode) {
// Perform operations on each nodes...

if($talentNode['isActivated'] && $talentNode['state'] === 10){
      $nodesActive[] = $talentNode;

    $perkName = $json2['Response']['definitions']['talentGrids'][''.$talentGridHash.'']['nodes'][''.$talentNode['nodeHash'].'']['steps']['0']['nodeStepName'];
    $perkIcon =  $json2['Response']['definitions']['talentGrids'][''.$talentGridHash.'']['nodes'][''.$talentNode['nodeHash'].'']['steps']['0']['icon'];

    if (strpos($perkName, 'Damage') == false) { 

$perkOutput .= '<div style="border:1px solid #999; border-radius:3px; padding:1px; float:left; margin-right:8px"><img src="http://www.example.com'.$perkIcon.'" height="22" title='.$perkName.'" /></div>'; 

    }

}

}

return $perkOutput;

}


getItemPerks(1);

1 个答案:

答案 0 :(得分:2)

$json2在函数中不可用,因此$nodes未定义。您需要将其作为参数传递,与$weaponSlot相同。

function getItemPerks($weaponSlot, $json){
    $nodes = $json //etc...
}

然后致电:getItemPerks(1, $json2);

或者调用另一个获取JSON并返回数组的函数:

function getItemPerks($weaponSlot){
    $json = getJSON();
    $nodes = $json //etc...
}

function getJSON(){
    $json = //get your JSON somehow
    return json_decode($json, true);
}

然后致电:getItemPerks(1);

请参阅PHP: Variable Scope