根据php中的条件替换数组的值

时间:2018-04-17 17:51:43

标签: php arrays if-statement

我有一个数组,我正在使用某种方法进行api调用。我有两种方法,我需要根据会话值选择1。

我的数组看起来像这样。

$order_params = array(
  'username' => 'test1',
  'password' => 'test2',
  'method' => 'Gateway1');

因此,如果会话值不为null,则方法需要为Gateway2,并且需要再传递一个参数。我正在做的是使用这种方式来更新数组。

$order_params = array(
  'username' => 'test1',
  'password' => 'test2',
  'method' => 'Gateway1');

if($_SESSION['userid'] != ''){
    $order_params['method'] = 'Gateway2';
    $order_params['proid'] = '222'
}

我需要确认我是否采取了正确的方式,或者是否有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:0)

  

我需要确认我是否采取正确的方式,或者是否还有更多   更好的方法。

如果没有看到所有代码,这真的很难说,但是你可以稍微整理一下代码并通过一次性设置你的值来略微改变它:

$order_params = [
    'username' => 'test1',
    'password' => 'test2',
    'method' => $_SESSION['userid'] != '' ? 'Gateway2' : 'Gateway1',
    'proid' => $_SESSION['userid'] != '' ? '222' : null,
];

所以一气呵成。

    如果您有用户ID,则
  • method设置为“Gateway2”,否则设置为默认值“Gateway1”
  • 如果你有一个用户ID,
  • proid设置为“222”,否则设置为默认空(只是设置了数组键,以后你不需要if (isset($order_params['proid'])))< / LI>
相关问题