0

First of all, sorry for the title, but I didn't know what to put exactly to describe the issue.

Back to the problem, this is what I want to get:

{"0":{"dep":"DIR","user":"10000008","seen":"0000-00-00 00:00:00"},"1":{"dep":"TES","user":"10000008","seen":"0000-00-00 00:00:00"}}

and this is the actual code I am using (that receives data from an input element as array) example:

<input type="text" name="dep[]" />
<input type="text" name="user[]" />

This is the main code I need to "fix":

$user = ($_POST['cc_user']);
$dep =  ($_POST['cc_dep']);

$cc = array();
for($i=0;$i<count($_POST['cc_dep']);$i++) {
    $cc = array();
    $cc['user'] = $user[$i];
    $cc['dep'] = $dep[$i];
    $cc['seen'] = '0000-00-00 00:00:00';
    $x = strval($i);
    $cc2["$x"] = $cc;

    unset($cc);
}

echo json_encode($cc2);

At the moment, this is the result instead of the one I want to get:

[{"user":"10000008","dep":"DIR","seen":"0000-00-00 00:00:00"},{"user":"10000001","dep":"admin","seen":"0000-00-00 00:00:00"}]

As you can see, the key of the array is not visible, and I need that for an integration on my website. I tried to specify the $i using:

  • (string)$i
  • stringval($i)
  • "$i"

but I didn't manage to solve the problem. Can someone help, even if it is something really easy?

Thanks in advance!

5
  • 1
    Why are you wrapping your $_POST with parenthesis? Commented Nov 26, 2018 at 17:09
  • I don't get it, what exactly are you asking? Commented Nov 26, 2018 at 17:12
  • Why not just $cc2[] = $cc at the end of your loop? Commented Nov 26, 2018 at 17:21
  • @WillardSolutions, you caught correctly and that's what I asked him that even he has not declared $cc2 variable and only used in loop. So without declaring variable will not give an effect :) Commented Nov 26, 2018 at 17:23
  • @NullPointer Please explain then, how was the OP able to get any result after calling echo json_encode($cc2);? Commented Nov 26, 2018 at 17:27

1 Answer 1

1

What you are probably looking for is forcing the JSON to be an object. Non-associative arrays (with all numerical keys) are displayed in JSON format without the key. In PHP numerical-ish strings will be converted to integers when used as array keys.
You can use additional parameter to make it a JSON object.

json_encode($cc2, JSON_FORCE_OBJECT)

Please take a look at the examples in the docs for json_encode

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

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.