PHP check variable if exists in array of json - php

Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!

You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]

You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}

Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}

Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));

Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';

Related

how to remove empty array value with key in php?

I am getting an array similar to the following one.
{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}
If form data values are null, I want to replace that key's value with the value of the next key.
Like above, after value 5, I have null values. It needs to be like this:
"final_data":["1","2","4","5","fill this with 6","remove this"]
"final_data":["1","2","4","5","6"] like this
I tried array_filter(), but it didn't help.
If the response is in json format then ...
$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}';
$array = json_decode($json, TRUE);
foreach($array as $index => $a) {
$array[$index] = array_filter($a);
}
print_r($array);
https://eval.in/866379
Update:
foreach($array as $index => $a) {
$array[$index] = array_value(array_filter($a));
}
https://eval.in/866522
try following code,
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
Try this array_filter() with array_map() and array_values()
<?php
$array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6"));
function filterMe($paraArr){
return array_values(array_filter($paraArr));
}
$array = array_map("filterMe",$array);
echo "<pre>";
print_r($array);
check the output here https://eval.in/866401

How to echo value of "id"?

{"2b44928ae11fb9384c4cf38708677c48":{
"id":"115",
"qty":3,
"option":"{\"color\":{\"title\":\"Color\",
\"value\":\"\"
}
}",
"price":150,
"name":"Nightwear",
"shipping":"5",
"tax":3,
"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg",
"coupon":"",
"rowid":"2b44928ae11fb9384c4cf38708677c48",
"subtotal":450
}
}
Hello everyone,
This is my array and I want to echo value of only "id" i.e. I want to get value as '115' of key- "id". Please guide me how to make a foreach for this one? I have tried lots of variations but none worked :(
TIA :)
UPDATE-
I have tried this but did not get any result:
foreach($res as $k=>$t)
{
echo $t["product_details"]["id"];
}
Before you can use the JSON as an array you need to convert it first. use json_decode() for that.
<?php
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true);
foreach($array as $key=>$value){
echo $value['id'];
}
?>
Assuming you have an array of objects like you provided in your post, I have put your object in an array for testing
<?php
$json = '[{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}},'.
'{"2b44928ae11fb9384c4cf38708677c48":{"id":"116","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}]';
$json = json_decode($json);
foreach ($json as $object){
$propsArray = get_object_vars($object);
reset($propsArray);
echo $object->{key($propsArray)}->id . "<br>\n";
}
exit;
this outputs
115
116
try a live demo (https://eval.in/836364)
$json='{"2b44928ae11fb9384c4cf38708677c48":{"id":"115","qty":3,"option":"{\"color\":{\"title\":\"Color\",\"value\":\"\"}}","price":150,"name":"Nightwear","shipping":"5","tax":3,"image":"http:\/\/localhost\/plus\/uploads\/product_image\/product_115_1_thumb.jpg","coupon":"","rowid":"2b44928ae11fb9384c4cf38708677c48","subtotal":450}}';
$array = json_decode($json, true); // convert json string to array
$result = array_column($array, 'id'); // find matching array key and return values in array
foreach ($result as $value) { // echo each value with foreach loop
echo $id . '<br>';
}

How to remove an object from JSON array in PHP

I have a JSON array. I want to delete the entry that have number 4 and return the left over array
$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);
foreach($fobj as $key => $value)
{
if (in_array(4, $fobj)) {
unset($fobj[4]);
}
}
echo $filters = json_encode($fobj );
But this echo does not give me what I want. I want it to return something like this:
{"1":1,"2":2}
You're removing the fourth value of the array, not the value. Use array_search instead
$filters = '{"1":1,"2":2,"3":4}';
$fobj = json_decode($filters, TRUE);
$search = array_search(4, $fobj);
if($search !== false) unset($fobj[$search]);
echo $filters = json_encode($fobj );
$index = array_search("4", $array);
unset($array[$index]);
http://php.net/manual/de/function.array-search.php
http://php.net/manual/de/function.unset.php
That's all. Hope it helps!

'where' like querying an array or object

[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]
I got an object like above. The thing I want to is select the object that's id is 1 for example. Like
select * from object where id=1
with SQL
How to do it?
I hope i got your question right.
Try the following
<?php
$array = json_decode('[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]');
foreach( $array as $v ) {
if( $v["id"] == 1 ) {
echo "I am ID 1";
break;
}
}
Decode your object (http://php.net/manual/it/function.json-decode.php) and then traverse your array with a foreach checking the id value inside of it with an if statement.
$obj_to_array = json_decode($json_object);
$target = '';
foreach($obj_to_array as $row){
if($row['id'] == 1)
$target = $row;
}
// $target holds your row with id = 1
$data = '[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$data = json_decode($data);
$id = 1;
$key = 'id';
$data = array_filter(
$data,
function($value) use ($key, $id) {
return ($value->$key == $id);
}
);
var_dump($data);
Decode the object using json_decode. Use the code below
<?php
$json='[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$p = json_decode($json,true);
$l=count($p);
for($i=0;$i<=$l;$i++){
$id=$p[$i]["id"];
if($id==1){
print_r($p[$i]); // WIll print the id if 1
}
}
Hope this helps you

Decoding json in array , editing array and encoding in json - PHP

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :
$json = json_decode(file_get_contents('all_json_files/jobs.json'), true);
foreach ($json as $key=>$row){
foreach ( $row as $key=>$row){
foreach ( $row as $key=>$row){
foreach ($row as $key=>$row){
if(strcmp($key,"security_block")==0)
{
foreach ($row as $k=>$r){
if(strcmp($k,"job_payload_hash")==0)
{
$row[$k]['job_payload_hash']=$base64String;
print_r($row);
}
}
}
}
}
}
}
print_r($json);
Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .
If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}
You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of #Ja͢ck .
this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result.
Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);

Categories