更改关联数组元素

时间:2015-03-26 13:17:25

标签: php arrays

我继承了以下代码:

  $sql_data_array = array('customers_id' => $customer_id,
                      'customers_name' => $order->customer['cname'],
                      'orders_status' => $order->info['order_status'],
                      'currency_value' => $order->info['currency_value']);

我需要做的是查看customer_status = 0,如果是,请使用currency_value ="是"。

但是,我不确定我是否应该在上述声明之前或之后这样做,而且我不清楚上面发生了什么,知道怎么做?

我知道=>运算符处理关联数组但我有点失去了。在做什么和解释发生了什么方面有任何帮助?

1 个答案:

答案 0 :(得分:1)

根据您给定的数组结构,数组格式看起来就像这两种可能的方式: -

1.Array
  (
     [customers_id] => customer id
     [customers_name] => name
     [orders_status] => 0
     [currency_value] => some digit
   )

2. Array
        (
            [0] => Array
                (
                    [customers_id] => customer id
                    [customers_name] => name
                    [orders_status] => 0
                    [currency_value] => some digit
                )

            [1] => Array
                (
                    [customers_id] => customer id
                    [customers_name] => name
                    [orders_status] => yes/no
                    [currency_value] => some digit
                )

        )

如果是第一个,那么使用: -

if($sql_data_array['orders_status'] == 0){
    $sql_data_array['currency_value'] = 'yes';
}

如果它像第二个那样使用: -

foreach ($sql_data_array1 as $key => $sql_data_arr){
    if($sql_data_arr['orders_status'] == 0){
        $sql_data_array1[$key]['currency_value'] = 'yes';
    }else{
    $sql_data_array1[$key]['currency_value'] = 'no';
}
}

输出是: -

1. Array
    (
        [customers_id] => customer id
        [customers_name] => name
        [orders_status] => 0
        [currency_value] => yes
    )

2. Array
(
    [0] => Array
        (
            [customers_id] => customer id
            [customers_name] => name
            [orders_status] => 0
            [currency_value] => yes
        )

   [1] => Array
    (
        [customers_id] => customer id
        [customers_name] => name
        [orders_status] => 1
        [currency_value] => no
    )
)