0

I have been trying to loop through an array. Inserting the values in two separate arrays $location and $name. But the $name array prints the index values as well, the $location works fine. Here's a sample of code

$j = 0;
foreach( $entities->results as $key => $value ) {

    if( stristr($value->vicinity, $key_stroke) ) {

        $location[$j]['place_id'] = $value->place_id;
        $location[$j]['vicinity'] = $value->vicinity;
    }

    if( stristr($value->name, $key_stroke) ) {

        $name[$j]['place_id'] = $value->place_id;
        $name[$j]['name'] = $value->name;
    }


 $j++; }

Here is the json output

{
    "locations": [
        {
            "place_id": "ChIJRQqyYRFZWjcRmxKd0esyj-k",
            "vicinity": "GS Road, Christian Basti, Guwahati"
        },
        {
            "place_id": "ChIJG5IvxhNZWjcRlkMD6lCJ64c",
            "vicinity": "GS Road, Ananda Nagar, Christian Basti, Guwahati"
        },
        {
            "place_id": "ChIJxQp72BZZWjcR98oQbFrdTII",
            "vicinity": "GS Road, Christian Basti, Guwahati"
        },
        {
            "place_id": "ChIJm5eeJBBZWjcRksI_VY9u1Qo",
            "vicinity": "Zoo Road, Sundarpur, Guwahati"
        }
    ],
    "names": {
        "1": {
            "place_id": "ChIJG5IvxhNZWjcRlkMD6lCJ64c",
            "name": "Ayush Medico's"
        },
        "2": {
            "place_id": "ChIJxQp72BZZWjcR98oQbFrdTII",
            "name": "Premananda Medico's"
        },
        "3": {
            "place_id": "ChIJm5eeJBBZWjcRksI_VY9u1Qo",
            "name": "Asaan Medicos"
        }
    }
}

Tried everything. What could be the problem??

5
  • 2
    Your if statement if( stristr($value->name, $key_stroke) ) seem to return false on the first iteration, which makes it omit the 0 index. When converting to json, that will make the "array" into an object instead since arrays can't have any gaps in the indexes. Commented Feb 7, 2018 at 6:53
  • 2
    When you combine the results, use array_values(), to reset the indexes and it be fine. Commented Feb 7, 2018 at 6:55
  • @LawrenceCherone it worked man..thanks a lot....but i have no idea what it just did. Would you mind explaining?? Please Commented Feb 7, 2018 at 6:59
  • 1
    @MagnusEriksson explained it and the docs explain array_values - returns all the values from the array and indexes the array numerically. Commented Feb 7, 2018 at 7:01
  • @MagnusEriksson thanks alot... Commented Feb 7, 2018 at 7:10

2 Answers 2

1

Solution 1: (Not efficient as the solution 2 below)

$j = 0;
$i = 0; // change over here
foreach( $entities->results as $key => $value ) {

    if( stristr($value->vicinity, $key_stroke) ) {

        $location[$j]['place_id'] = $value->place_id;
        $location[$j]['vicinity'] = $value->vicinity;
        $j++;
    }

    if( stristr($value->name, $key_stroke) ) {

        $name[$i]['place_id'] = $value->place_id; // change over here
        $name[$i]['name'] = $value->name;         // change over here
        $i++;
    }

}

Solution 2:

Pass the $name array to php's inbuilt funtion array_values() which in turn will return you with the array index starting from 0.

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

1 Comment

The first solution still encodes $location as object in JSON if the first if condition is false for some $value.
0

If you look closely you will notice that in JSON, the value of "location" is an array but the value of "names" is an object (having the properties "1", "2" and "3"). This happens because $location is an array that contains 4 values associated with the keys 0, 1, 2 and 3 while $name is an array whose keys are 1, 2 and 3.

Because JSON is a subset of JavaScript and JavaScript arrays allow only numeric keys (starting from 0), PHP encodes as JavaScript arrays only the arrays that have numeric consecutive keys starting from 0. All the other arrays are encoded in JSON as objects.

This is written in the documentation of json_encode():

Note:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

The reason why $names does not contain the key 0 is the if condition that wraps the assignment:

if( stristr($value->name, $key_stroke) ) {

The similar condition that wraps the assignment of $location[$j] can make $location behave similar with different input data.

If you want to get arrays in the JSON-encoded output you have to build them in a way that ensures the keys are consecutive integers starting with 0. This is easier than it sounds. There is no need to keep track of the keys, just build the inner arrays in a different way and let PHP generate the keys of the outer arrays:

$location = array();
$name     = array();

foreach( $entities->results as $key => $value ) {

    if( stristr($value->vicinity, $key_stroke) ) {

        $location[] = array(
           'place_id' => $value->place_id,
           'vicinity' => $value->vicinity,
        );
    }

    if( stristr($value->name, $key_stroke) ) {

        $name[] = array(
            'place_id' => $value->place_id,
            'name'     => $value->name,
        );
    }
}

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.