0

I want to dynamically create a short array with a list of objects. This is for a POST request with the Guzzle client. That's why I need it in a short array.

example of a Guzzle post request:

 $res = $this->client->request($methode, $request_url, [
            'form_params' => [
                'param' => 'value'
            ]
         ]);

Problem case:

I have got a List: Params of Objects: Param. Param has three attributes id, name, link_id.

Let's say the List has three Object.

param(1, email, 1)
param(2, username, 1)
param(3, password, 1)

I want to dynamically create from the list an array with the short array syntax.

Example(Pseudo):

for each params as param

 [
   'form_params' => [
     param->name => 'value'
   ]
 ]

the result of this code will be like this

 [
   'form_params' => [
     'email' => 'value',
     'username' => 'value',
     'password' => 'value'
   ]
 ]

Code example:

$params = array(
   "param" => array (
      "id" => "1",
      "name" => "username",
      "link_id" => "1",
   )
);

$value = '';
$shortarray = '';
foreach($params as $key => $param){
  $shortarray .= $param->name . '=>' . $value . ',';
}

$postParams = ['form_params' => [ .  $shortarray . ]];

I really could use some help. Thank you in advance.

melkawakibi
  • 823
  • 2
  • 11
  • 26

2 Answers2

1

If you want to just show short array syntax than this solution may helps you to resolve you problem.

https://stackoverflow.com/a/35207172/4781882

Gautam D
  • 330
  • 3
  • 15
0

I am not quite sure why you require it be a "short array", but here's a solution...

I assume this is a web form, yes?

So let's assume you name your forms in a way that is usable, like:

<form method="POST" action="yourform.html">
Line 1 <input name="email1"> | <input name="user1"> | <input name="password1">
<br/>-------<br/>
Line 2 <input name="email2"> | <input name="user2"> | <input name="password2">
<br/>-------<br/>
Line 3 <input name="email3"> | <input name="user3"> | <input name="password3">
</form>

Then...

for($i = 1; $i <= 3; $i++ {
  $postparms[] = ['email' => $_POST['email'.$i], 'user' => $_POST['user'.$i], 'password' => $_POST['password'.$i] ];
}

print_r($postparms);
  • Thank you for your reply, I'm building a short array for a POST request with GuzzleClient. This is not what I'm looking for. Sorry I'll add more context to it. – – melkawakibi May 26 '17 at 11:44