Search array with specific key value pair [duplicate] - php

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 3 years ago.
Assume I have this array list in php
[
{
"id": "1",
"name": "test1",
},
{
"id": "2",
"name": "test2",
},
]
How can I easily return the id that have name=test1?

Try using array_search(). First, get the place of the id, name pair and get the content of the id field next.
//Get the key of the 'id, name' pair
$key = array_search('test2', array_column($input, 'name'));
//Get the id beloning to the name
$id = $input[$key]->id;
A working example here.

I assume you have multilevel array, so you do using foreach function as below.
$x= array(array('id'=>'1','name'=>'test1'),array('id'=>'2','name'=>'test2'));
foreach($x as $value){
if($value['id'] =="1" && $value['name'] == "test1"){
// Do your stuff
}
}

Related

PHP array_filtered acces object [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 14 days ago.
I'm trying to filter array from DB and I've got this postman response:
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}}
How I can access to id, key, value?
My code here:
$start = array_filter($array, function ($var) {
return ($var['key'] == 'emails_html_body_start');
});
echo json_encode($start);
Your question is a bit unclear ... So the upper code is what is sent by the lower code snippet? So the cho json_encode($start); is what produces the upper json data?
If so, then you obviously need to json decode that data again to be able to access a property inside that structure:
<?php
$input = <<<JSON
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}
}
JSON;
$data = json_decode($input, true);
$output = $data[1]['id'];
print_r($output);
The output obviously is:
3

How to get keys from JSON [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I'm using Laravel. I have JSON returned from Database.
I would like to get key names like "id / name / email / revision" from following JSON.
{
"id": "000",
"records": [
{
"id": 23,
"name": "hoge",
"email": "Hoge#alk.jp",
"revision": 0
},
{
"id": 24,
"name": "zaku",
"email": "zaku#alk.jp",
"revision": 0
},
]
}
Please let me know how to get key names.
Thank you.
You should get the keys with collection get key by code following:
collect($data->records)->keys();
This will return
id
name
email
revision
More detail you can check here: https://laravel.com/docs/8.x/collections#method-keys
Use json_decode to convert it to an array:
$array = josn_decode($jsonVariable, true);
Then use foreach:
foreach($array['records'][0] as $key => $value){
$keys[] = $key;
}
or array_keys:
array_keys($array['records']);
or collect to get keys:
$keys = collect($array['records'])->keys();

How to see if json array contains a value? [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
json_decode to array
(12 answers)
Closed 2 years ago.
So, I'm new to php and while testing some services, I have a JSON object:
{
"entry": [
{
"authorId": "#me",
"type": "USER"
},
{
"authorId": "514",
"type": "USER"
},
{
"authorId": "516",
"type": "USER"
}
],
"count": 3,
"totalResults": 3
}
and I need to assert that '#me' is part of this object. I tried something like:
$Obj->assertTrue(array_key_exists('#me', $response['entry']));
but it won't just work. Can someone give me a hint regarding this? Thank you
EDIT:
'#me' can be anywhere in the array, not on the first position and I'm asking this for a a test in codecept, so I need to an assert directly
You can loop through your result set to check it for each entry.
function checkEntries($object, $search) {
$object = json_decode($object, true);
foreach($object['entry'] as $entry) {
if ($entry['authorId'] == $search) {
return true;
}
}
return false;
}
Or you can use this:
PHP multidimensional array search by value

array_filter adds additional index in my array, how to get rid of it? [duplicate]

This question already has answers here:
json_encode PHP array as JSON array not JSON object
(4 answers)
Closed 4 years ago.
I have a array created from json
$fullResult = json_decode('[{"qid":"1", "result":"helo"}, {"qid":"2", "result":"ad"}, {"qid":"3", "result":"testing"}, {"qid":"4", "result":"dd"}]');
function filterArray($value){
global $id;
return ($value->qid > $id);
}
$filteredResult = array_filter($fullResult, 'filterArray');
The $id is 2
When I echo json_encode($fullResult);
The result is
[ {"qid": "1", "result": "helo"},
{"qid": "2", "result": "ad"},
{"qid": "3", "result": "testing"},
{"qid": "4", "result": "dd"} ]
However, when I echo json_encode($filteredResult); the result as below (e.g. having the additional index.
{ "2":{"qid":"3","result":"testing"},
"3":{"qid":"4","result":"dd"} }
I want it to be as below instead
[ {"qid":"3","result":"testing"},
{"qid":"4","result":"dd"} ]
How could I achieve that?
Instead of
echo json_encode($filteredResult);
try something along the lines of,
echo json_encode(array_values($filteredResult));
array_values would eliminate the unwanted indexes.
array_filter will retain the key. If you want to make it a simple array, you can use array_values
$filteredResult = array_values(array_filter($fullResult, 'filterArray'));
echo json_encode($filteredResult);
This will result to:
[{"qid":"3","result":"testing"},{"qid":"4","result":"dd"}]
Doc: array_values
You can set it by loop also.
$singleArray = array();
foreach ($filteredResult as $key => $value){
$singleArray[] = $value;
}
echo json_encode($singleArray);exit;

Get a key from an JSOn object inside another JSON object only knowing it's position [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed last year.
So I have the following JSON Object as an example:
{
"employees": {
"employee300": {
"number" : "example",
"Name" : "example",
"position" : 1
},
"employee456": {"number" : "example",
"Name" : "example",
"position" : 2},
"employee120":{"number" : "example",
"Name" : "example",
"position" : 3}
}
}
I only have the position and I want to get the employee's id. For example, I have the position number that is 2 and I need to get the id that is "employee456".
I know there are a lot of key functions in PHP, but I would like to know how I can make my code work in my scenario.
I can also convert the json to an array if there is a solution to it that way.
I'm not sure whether you want to do this in JS or PHP, going to assume the latter.
<?php function get_employee_at_pos($employees, $pos)
{
foreach ($employees as $key => $value) {
if ($value['position'] == $pos) {
return $key;
}
}
return false;
}
use var keys = Object.keys(obj) to get the keys, then use the myobject[keys[1]]. (1 corresponds to position - 1).
EDIT: in php
$keys = array_keys(myobject); and use $myobject[$keys[1]]
EDIT 2: in php, you need to load the json in an array
$myjson = json_decode(file_get_contents("yourfile.json"), true); // loads yourfile.json and converts to a php array.

Categories