codeigniter - 从函数中获取所需的数组,结果是数组列表

时间:2017-08-16 02:48:16

标签: php arrays codeigniter

所以我有这个功能getList。我想要完成的是:

  1. 获取函数stateApi,其结果是数组列表。(此函数是API。)
  2. 只从数组列表中获取所需的数组。
  3. 保存到数据库。
  4. stateApi功能的结果是:

    Array
    (
    [ack] => Array
        (
            [ackstatus] => OK
            [ackreason] => Array
                (
                )
    
        )
    
    [type] => 01
    [states] => Array
        (
            [statecount] => 3
            [state] => Array
                (
                    [0] => Array
                        (
                            [@attributes] => Array
                                (
                                    [cd] => 01
                                    [name] => America
                                    [desc] => USA
                                )
    
                        )
    
                    [1] => Array
                        (
                            [@attributes] => Array
                                (
                                    [cd] => 02
                                    [name] => China
                                    [desc] => CHN
                                )
    
                        )
    
                    [2] => Array
                        (
                            [@attributes] => Array
                                (
                                    [cd] => 03
                                    [name] => Russia
                                    [kana] => RSA
                                )
    
                        )
    
                )
        )
    )
    

    我唯一想要得到的是state数组的内容。 例如:

    [0] => Array
    (
         [@attributes] => Array
         (
              [cd] => 01
              [name] => America
              [desc] => USA
         )
     )
    [1] => Array
    (
         [@attributes] => Array
         (
              [cd] => 02
              [name] => China
              [desc] => CHN
         )
     )
    [2] => Array
    (
         [@attributes] => Array
         (
              [cd] => 03
              [name] => Russia
              [kana] => RSA
         )
     )
    

    这是我能做的代码;

    //TODO:
    //call api
    $prefapi = $this->itpApi->getPrefectures();
    
    foreach ($prefapi as $pref) {
        $data = $pref["states"]["state"];
    }
    //Save DB
    $this->db->insert('Prefecture',$data);
    

2 个答案:

答案 0 :(得分:0)

如果你想在一行中插入所有的状态数组,你可以得到它,如下所示: -

 $prefapi['states']['state'];

或者如果你想逐一进行,你可以这样做

 foreach($prefapi['states']['state'] as $value)
    {
       then your insert query
     }

答案 1 :(得分:0)

您可以通过添加一个数组变量来完成此操作。

$insertData = array(); 
$prefapi = $this->itpApi->getPrefectures();

foreach ($prefapi as $pref) {
    $insertData[] = $pref["states"]["state"];
}

$this->db->insert('Prefecture',$insertData);