在数组php foreach

时间:2017-05-02 10:21:36

标签: php arrays

我有一个带动态数组的函数。

function doIt($accountid,$targeting){
    $post_url= "https://url".$accountid."/";
    $fields = array(
          'name' => "test",
          'status'=> "PAUSED",
          'targeting' => array(
            $targeting
          ),
      ); 
   $curlreturn=curl($post_url,$fields);
};

我想在foreach循环中动态构建数组“$ fields”。像那样:

$accountid="57865";    
$targeting=array(
                      "'device_platforms' => array('desktop'),'interests' => array(array('id' => '435345','name' => 'test')),",
                      "'device_platforms' => array('mobile'), 'interests' => array(array('id' => '345345','name' => 'test2')),",
                    );

foreach ($targeting as $i => $value) {
        doit($accountid,$value);
    }

问题是,函数中的数组将无法正确填充。如果我在函数中输出数组,我得到类似的东西:

....[0] => array('device_platforms' => array('desktop'),'custom_audiences'=> ['id' => '356346']), ) 

开头[0]应该是问题所在。什么想法我做错了什么?

1 个答案:

答案 0 :(得分:1)

希望这会帮助你。问题在于您定义$targeting数组的方式。您不能拥有多个具有相同名称的键

更改1:

$targeting = array(
array(
    'device_platforms' => array('desktop'),
    'interests' => array(
        array('id' => '435345', 
            'name' => 'test')),
    ),
array(
    'device_platforms' => array('mobile'),
    'interests' => array(
        array('id' => '345345', 
            'name' => 'test2'))
    )
);

更改2:

$fields = array(
        'name' => "test",
        'status' => "PAUSED",
        'targeting' => $targeting //removed array
    );

Try this code snippet here this will just print postfields

<?php

ini_set('display_errors', 1);

function doIt($accountid, $targeting)
{
    $post_url = "https://url" . $accountid . "/";
    $fields = array(
        'name' => "test",
        'status' => "PAUSED",
        'targeting' => $targeting
    );
    print_r($fields);
}

$accountid = "57865";
$targeting = array(
    array(
        'device_platforms' => array('desktop'),
        'interests' => array(
            array('id' => '435345', 
                'name' => 'test')),
        ),
    array(
        'device_platforms' => array('mobile'),
        'interests' => array(
            array('id' => '345345', 
                'name' => 'test2'))
        )
);
foreach ($targeting as $i => $value)
{
    doit($accountid, $value);
}