dqcd84732 2014-06-11 00:08
浏览 40
已采纳

使用数组的函数没有效果[关闭]

I have problem with function , if i use the script and no works as function works fine , but if use it as function no works me and no show the values right , for example with the function show me only 1 value and if don´t use as function show me all values right , i don´t know if the problem it´s with arrays inside function or what

<?php

function update($array_1)
{

$val=explode(","$array_1);


foreach ($val as $key=>$value) 
{   
$values_db[]="".$key."";
}

foreach($_POST['opt'] as $key2=>$value2)
{
$values_post[]="".$key2."";
}

$aa=array_diff($values_db,$values_post);
$bb=array_intersect($values_db,$values_post);

foreach($aa as $aaa)
{
print "<b>".$aaa." ".$opt[$aaa]."</b><br>";
}

foreach($bb as $bbb)
{   
print "".$bbb." ".$_POST['opt'][$bbb]."<br>";   
}


}

update("val1,val2");

?>

The problem it´s if use as function only , i think if howewer the values i send by POST in function no works fine and if use the script as no function receive ok

Regards

  • 写回答

1条回答 默认 最新

  • duanaigua4033 2014-06-11 00:32
    关注

    My first assumption is that when you put your code into a function, the variables you are accessing are no longer available inside the function's scope ($values_db and $values_post). You've also referenced $opt[$aaa] and I can't see where you're defining $opt. This might be another variable that you are using outside the function and when you wrap your code into a function it is no longer available.

    In your case, the quickest solution would be to declare these variables as global so that you can access them as you normally would inside the function:

    function update($array_1) {
        global $values_db, $values_post, $opt;
        // ...
    }
    

    Other options are that you could use internal variables inside the function and return the values from the function, adding them to your array outside the function:

    function update($array_1) {
        $values_db = array();
        $values_db[] = 'world!';
        return $values_db; 
    }
    
    $values_db = array('Hello ');
    $values_db = array_merge($values_db, update($your_other_array)); // ['Hello ', 'world!']
    

    Your third option is to pass those variables by reference so that they can be updated in the global scope from within the function:

    function update($array_1, &$values_db, &$values_post, &$opt) {
        // ...
    }
    
    update("val1,val2", $values_db, $values_post, $opt);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)