0

I have following PHP code, to create JSON with foreach out of an array:

$array = array('one', 'two', 'three', 'four');

foreach ($array as $key => $value) {
    $temp = array(
                'text' => 'Hello', 
                'text1' => 5,
                'collect' => array(
                                $value => array(
                                            'xx' => 'yy',
                                            'key' => $key
                                        )
                            )
            );


    echo json_encode($temp);
}

The Output is this:

{
    "text":"Hello",
    "text1":5,
    "collect":{"one":{"xx":"yy","key":0}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"two":{"xx":"yy","key":1}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"three":{"xx":"yy","key":2}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"four":{"xx":"yy","key":3}}
}

But i want this:

{
    "text":"Hello",
    "text1":5,
    "collect": {
        "one":{"xx":"yy","key":0},
        "two":{"xx":"yy","key":1},
        "three":{"xx":"yy","key":2},
        "four":{"xx":"yy","key":3}
    }
}

I get single 4 single JSON Objects, but i need only one with an collect object.

I don't get it...

0

3 Answers 3

1

I'd like to educate readers on a couple alternative methods as well as highlight that the other two answers needlessly instantiate the collect subarray prior to the loop (Sahil's answer does this twice for some reason).

The initial input array and the static elements of the result array should be placed at the start as the other answers do. Purely due to personal preference, I'll be using short array syntax.

Inputs:

$array=['one','two','three','four'];
$result=['text'=>'Hello','text1'=>5];   // <-- no 'comment' element declared

Now for the different methods that traverse $array and build the dynamic elements of the result.

Method #1: array_walk()

array_walk($array,function($v,$k)use(&$result){
    $result['collect'][$v]=['xx'=>'yy','key'=>$k];
});

Method #2: array_map()

array_map(function($k,$v)use(&$result){
    $result['collect'][$v]=['xx'=>'yy','key'=>$k];
},array_keys($array),$array);

Array map is less efficient because it requires an additional array to be passed to the function.

Method #3: foreach()

foreach($array as $k=>$v){
    $result['collect'][$v]=['xx'=>'yy','key'=>$k];
}

$result at this point looks like this:

array (
    'text' => 'Hello',
    'text1' => 5,
    'collect' => array (
        'one' => array ( 'xx' => 'yy', 'key' => 0 ),
        'two' => array ( 'xx' => 'yy', 'key' => 1 ),
        'three' => array ( 'xx' => 'yy', 'key' => 2 ),
        'four' => array ( 'xx' => 'yy', 'key' => 3 )
    )
)

foreach() is the simplest and easiest to read for this case, but it important to understand and compare versus php's array functions to ensure you are using the best method for any given project.

For anyone wondering what the & is doing in use(&$result), that is a reference which is used in the anonymous function (aka closure) to make the $result variable "modifiable" within the function.

Finally convert to json using json_encode() and display with echo:

echo json_encode($result);

All of the above methods product the same desired output:

{"text":"Hello","text1":5,"collect":{"one":{"xx":"yy","key":0},"two":{"xx":"yy","key":1},"three":{"xx":"yy","key":2},"four":{"xx":"yy","key":3}}}

Here is the Demo of all three methods

Sign up to request clarification or add additional context in comments.

Comments

0

Try this simple code ,in which we have a declaration before foreach.

Try this code snippet here

<?php

ini_set('display_errors', 1);
$array = array('one', 'two', 'three', 'four');

$temp = array(
    'text' => 'Hello',
    'text1' => 5,
    'collect' => array()
);
$collect = array();
foreach ($array as $key => $value)
{
    $collect[$value] = array(
        'xx' => 'yy',
        'key' => $key
    );
}
$temp["collect"]=$collect;
echo json_encode($temp);

Output:

{
    "text": "Hello",
    "text1": 5,
    "collect": {
        "one": {
            "xx": "yy",
            "key": 0
        },
        "two": {
            "xx": "yy",
            "key": 1
        },
        "three": {
            "xx": "yy",
            "key": 2
        },
        "four": {
            "xx": "yy",
            "key": 3
        }
    }
}

Comments

0

You need to loop through and append these value arrays to the 'collect' key of your temp array.

$array = array('one', 'two', 'three', 'four');
$temp = array(
    'text' => 'Hello', 
    'text1' => 5,
    'collect' => array()
);

foreach ($array as $key => $value) {
    $temp['collect'][$value] = array(
        'xx' => 'yy',
        'key' => $key
    );
}

echo json_encode($temp);

Here is the demo: https://eval.in/788929

1 Comment

No not working. Result is: [{"text":"Hello","text1":5,"collect":{"one":{"xx":"yy","key":0}}},{"text":"Hello","text1":5,"collect":{"two":{"xx":"yy","key":1}}},{"text":"Hello","text1":5,"collect":{"three":{"xx":"yy","key":2}}},{"text":"Hello","text1":5,"collect":{"four":{"xx":"yy","key":3}}}]

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.