0

OK let's say I have this example of JSON

{
    "result": [
        {
            "id": 1,
            "title": "Random Title 1",
            "description": "Random Description 1"
        },
        {
            "id": 4,
            "title": "Random Title 2",
            "description": "Random Description 2"
        },
        {
            "id": 10,
            "title": "Random Title 3",
            "description": "Random Description 3"
        }
    ]
}

Do you notice how the IDs are spaced out? So if I wanted to get the 2nd one "Random Title 2" it wouldn't be [4] but [2]. Some of my JSON "ids" are skipping because I edit the JSON file... ANyway right now, I want to get the title of a JSON element based on the id. Each JSON element has a different ID.

Here's what I do right now:

$string = file_get_contents("achievements.json");
$json_a=json_decode($string,true);

$getID = $ID_number;

$getit = $json_a['testJSON'][$getID]['title'];

Now, I have the $ID_number but it won't be the same as the array number. The above is wrong... how do I fix it so I search by id

1
  • With foreach and an if. Commented Jan 13, 2013 at 21:36

2 Answers 2

1
foreach ($json_a['tstJSON'] as $element) {
    if ($element['id'] == $getID) {
        $getit = $element['title'];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this was easy enough and simple. Thank you.
You do know that you're doing an assignment in an if statement right?
1

Here is my answer:

<?php

$json = <<<EOF
{
    "result": [
        {
            "id": 1,
            "title": "Random Title 1",
            "description": "Random Description 1"
        },
        {
            "id": 4,
            "title": "Random Title 2",
            "description": "Random Description 2"
        },
        {
            "id": 10,
            "title": "Random Title 3",
            "description": "Random Description 3"
        }
    ]
}
EOF;

$arr = json_decode($json,true);
$res = $arr['result'];

function search_by_key_and_value($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, search_by_key_and_value($subarray, $key, $value));
    }

    return $results;
}

print("<pre>");
print_r($res);
print("</pre>");

print("<hr />");
$result = search_by_key_and_value($res,"id",4);

print("<pre>");
print_r($result);
print("</pre>");

?>

Hope this is what you need

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.