manuel_k
manuel_k

Reputation: 573

Remove the only index on an array php

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?

Upvotes: 2

Views: 67

Answers (3)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Simply use array_values like as

echo json_encode(array_values($array));

Upvotes: 6

MasoodRehman
MasoodRehman

Reputation: 715

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

print_r(json_encode($newArray));

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

Upvotes: 0

CiaranSynnott
CiaranSynnott

Reputation: 928

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}]

Upvotes: 0

Related Questions