[英]insert variable in array php foreach
i have a function with a dynamic array. 我有一个动态数组的功能。
function doIt($accountid,$targeting){
$post_url= "https://url".$accountid."/";
$fields = array(
'name' => "test",
'status'=> "PAUSED",
'targeting' => array(
$targeting
),
);
$curlreturn=curl($post_url,$fields);
};
And i want to build the array "$fields" dynamically within a foreach loop. 我想在foreach循环中动态地构建数组“ $ fields”。 Like that: 像那样:
$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);
}
The Problem is, that the array within the function will not be correctly filled. 问题是,函数内的数组将无法正确填充。 If i output the array in the function i get something like: 如果我在函数中输出数组,我会得到类似:
....[0] => array('device_platforms' => array('desktop'),'custom_audiences'=> ['id' => '356346']), )
The beginning [0] should be the problem. 开头[0]应该是问题所在。 Any ideas what im doing wrong? 任何想法我做错了什么?
Hope this will help you out. 希望这对您有所帮助。 The problem was the way you are defining $targeting
array. 问题是您定义$targeting
数组的方式。 You can't have multiple keys with same name 您不能有多个同名钥匙
Change 1: 变更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'))
)
);
Change 2: 变更2:
$fields = array(
'name' => "test",
'status' => "PAUSED",
'targeting' => $targeting //removed array
);
Try this code snippet here this will just print postfields
在 this will just print postfields
尝试此代码段, 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.