经过漫长的一天调试和尝试错误,尝试使用嵌套数组和资源项的Guzzle6 post搜索一个好方法。
我在Guzzle6文档中发现,数据需要与[“多部分”=> []一起发布。当我得到单个数组项时,这是可行的。但我有这样的嵌套数组项目。
[
[firstname] => 'Danny',
[phone] => [
[0] => [
[phone] => 0612345678
]
]
[picture] => '/data/...'
]这需要作为Guzzle6的多部分格式,如下所示。
[
[
'name' => 'firstname',
'contents' => 'Danny'
],
[
'name' => 'phone[0][phone]
'contents' => '0612345678'
],
[
'name' => 'picture',
'contents' => fopen('....', 'r')
]
]我想在没有特殊技巧的情况下解决这个问题。是否有好的方法将带有嵌套数组和资源的post数组发送到多部分数组。
发布于 2017-01-11 23:07:43
经过一整天的工作,我得到了我的多部分表单数据数组。对于每个有相同问题的人,下面是代码。在$output中,数据中有一个字段数组。它可以用于“多部分”的=> $output和口香糖。
$output = [];
foreach($data as $key => $value){
if(!is_array($value)){
$output[] = ['name' => $key, 'contents' => $value];
continue;
}
foreach($value as $multiKey => $multiValue){
$multiName = $key . '[' .$multiKey . ']' . (is_array($multiValue) ? '[' . key($multiValue) . ']' : '' ) . '';
$output[] = ['name' => $multiName, 'contents' => (is_array($multiValue) ? reset($multiValue) : $multiValue)];
}
}发布于 2017-03-08 00:30:34
我在上面使用了@DannyBevers的答案,但发现它不适用于需要作为多部分发送的深嵌套数组,因此,下面是另一种解决方案:
// fake nested array to be sent multipart by guzzle
$array = array(
'title' => 'Test title',
'content' => 'Test content',
'id' => 17,
'Post' => array(
0 => array(
'id' => 100027,
'name' => 'Fake post title',
'content' => 'More test content ',
'Comments' => array (
0 => 'My first comment',
1 => 'My second comment',
2 => 'My third comment'
)
),
1 => array(
'id' => 100028,
'name' => 'Another fake post title',
'overall' => 2,
'content' => 'Even More test content ',
'Comments' => array (
0 => 'My other first comment',
1 => 'My other second comment',
)
)
)
);
$flatten = function($array, $original_key = '') use (&$flatten) {
$output = [];
foreach ($array as $key => $value) {
$new_key = $original_key;
if (empty($original_key)) {
$new_key .= $key;
} else {
$new_key .= '[' . $key . ']';
}
if (is_array($value)) {
$output = array_merge($output, $flatten($value, $new_key));
} else {
$output[$new_key] = $value;
}
}
return $output;
};
$flat_array = $flatten($array);
$data = [];
foreach($flat_array as $key => $value) {
$data[] = [
'name' => $key,
'contents' => $value
];
}
$response = $guzzle->request($type, $get, array('multipart' => $data));发布于 2018-12-11 20:25:29
@见https://github.com/guzzle/guzzle/issues/1679#issuecomment-342233663
使用http_build_query获取扁平的名称,然后构建多部分。
$multipart = [];
$vars = explode('&', http_build_query($postData));
foreach ($vars as $var) {
list($nameRaw, $contentsRaw) = explode('=', $var);
$name = urldecode($nameRaw);
$contents = urldecode($contentsRaw);
$multipart[] = ['name' => $name, 'contents' => $contents];
}https://stackoverflow.com/questions/41587134
复制相似问题