0

I wish to add key/value pairs into the same index of an array inside a loop.

Something Like this:

$attributes = array();
    for($i=0;$i<3;$i++)
    {
        array_push($attributes, array("title" => "this is content" . $i));
    }

except that the above would add new arrays to the original one. The output of above would be:

[{"title":"this is content0"},{"title":"this is content1"},{"title":"this is content2"}]

What I need is something like the following:

{"title1":"Hello World!","title2":"yoyoyyooyy"}

So the array still has a single index but multiple key/value pairs in that index separated by a comma.

Please HELP!!!

1
  • 1
    So you are saying you want the value of $attributes[n] to be be a serialized object rather than an array? I would create the object then json_encode the whole thing and store the encoded object in $attributes. Commented Aug 21, 2014 at 11:41

3 Answers 3

4

Please try this:

$attributes = array();
for ($i = 0; $i < 3; $i++)
{
      $attributes['title'][] = "content".$i;
}
Sign up to request clarification or add additional context in comments.

Comments

0
$attributes = array();
    for($i=0;$i<3;$i++)
    {
        $attributes["title".$i]= "this is content".$i;
    }

this will help you no need to use array push

1 Comment

Thank you this is a very simple solution. Can't realise I didn't think of it.
0

I'm not sure at all what do you want to achieve...

So the array still has a single index but multiple key/value pairs in that index separated by a comma.

Taking it literally would you want something like this? (that would be serializing)

$attributes:
    array(1) {
      [0]=> "Title1,This is content0,Title2,This is content1,Title3, (...)"
      string(n)

Because if so, you'd just need to do this:

$index_values = array();
for ($i=0; $i<N; $i++)
{
     $index_values[] = "Title" . $i;
     $index_values[] = "This is content". $i;
}

then

$attributes[0] = implode(",", $index_values);

Alternatively, you could do what other fellow users told above, then json_encode($array) that resulting array into first index of destination array.

Note: as far as I know, you can't have spare key/pair values without being encapsulated inside an structure like an array or an object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.