正确编码Json?

Alright, So I'm redoing my question so people can understand what I'm trying to do.

Search.php

<?php
$getItems = file_get_contents('Items.json');
if(isset($_GET['searchVal'])){
    $getItems2 = json_decode($getItems, true);
    $data2 = array("items" => array(array()));
    foreach($getItems2['items'] as $data){
        if(strpos($data['name'], $_GET['searchVal'])){
             $data2 = array("items" => array(array($data)));
        }
    }
    echo json_encode($data2,JSON_UNESCAPED_SLASHES);
} else{
    echo $getItems;
}

Problem: Doesn't get all items which have that name, gets only one.

Search is done, now I have to fix somehow to get all items which match the name. How could I do that?

You have the following inside a loop:

$data2 = array(...)

...and then you reference $data2 outside the loop.

Of course, it will only contain the last entry, because that line is overwriting $data2 with new data each time the loop iterates.

If you want to keep all the records from the loop, use

$data2[] = array(...)

instead.

[EDIT]

Further guessing as to what you actually want your JSON to look like, I guess you want all the records to be in the items array?

So in that case, let's rewrite your $data2 line, as follows:

$data2['items'][] = array($data);

This will add all the data arrays to your items array in $data2. I will note that your array structure is really convoluted -- too many nested arrays, which makes it difficult to be sure I'm giving you the answer you want even now, but hopefully if it isn't exactly right, it will show you the direction you need to go.

You'll also want to have an additional line at the top of your code to initialise $data2, like this:

$data2 = array('items'=>array());

This should be somewhere at the top of the code, before $data2 is used, and outside of the loop.