2

I am trying to print an array on php when I use

echo json_encode($array);

It shows me this:

{
    "1": {
        "x": "145",
        "y": "20"
    },
    "2": {
        "x": "145",
        "y": "40"
    }
}

but I want this:

{
    {
         "x":"145",
         "y":"20"
    },
    {
        "x":"145",
        "y":"40"
    }
}

How to do that?

2
  • So how would you get a specific index value then? Commented Nov 13, 2015 at 9:22
  • 1
    the json you want is not quite valid, you have two objects nested in another object Commented Nov 13, 2015 at 9:30

3 Answers 3

6

Simply use array_values like as

echo json_encode(array_values($array));
Sign up to request clarification or add additional context in comments.

2 Comments

$your_json it's an array not a string
I'm not sir. Well glad it helped you.
0

Inorder to achieve this you need to strutire your array like this;

$arr = array(array("x"=>145, "y"=>20),array("x"=>145, "y"=>40));

or

$arr = array();
$arr[] = array("x"=>145, "y"=>20);
$arr[] = array("x"=>145, "y"=>20);

This will then give you the following for json_encode

[{"x":145,"y":20},{"x":145,"y":20}]

Comments

0
$newArray = array();
foreach ($array as $key => $val)
{
    $newArray[] = $val;
}

print_r(json_encode($newArray));

**Result**: [{"x":"145","y":"20"},{"x":"145","y":"40"}]

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.