How to check JSON String based on another JSON String? - php

I'd like to do a loop with these JSON strings.
$json_m = '[
{"name":"1","value":"1"},
{"name":"2","value":"2"},
{"name":"3","value":"3"},
{"name":"4","value":"4"},
{"name":"5","value":"5"},
]';
$json_a = '[
{"name":"1-m","value":"1"},
{"name":"2-m","value":"3"},
{"name":"3-m","value":"5"},
]';
I do a loop and on $json_m. If the value exists in both JSON, I set the parameter to TRUE
This is my current code:
$jm = json_decode($json_m, true);
$ja = json_decode($json_a, true);
$i = 0;
$is_exist = FALSE;
foreach($jm as $rows ){
if($rows["value"] == $ja[$i]["value"]){
$is_exist = TRUE;
}
$dataadd = array ( 'ID' => $i,
'NAME' => $rows["value"],
'STATUS' => $is_exist
);
$i++;
}
This script returns as all FALSE, based on my example the STATUS should return like this:
TRUE
FALSE
TRUE
FALSE
TRUE
Do I miss something or what? Any help is greatly appreciated.

You can do using array_search like below
$json_m = '[
{"name":"1","value":"1"},
{"name":"2","value":"2"},
{"name":"3","value":"3"},
{"name":"4","value":"4"},
{"name":"5","value":"5"}
]';
$json_a = '[
{"name":"1-m","value":"1"},
{"name":"2-m","value":"3"},
{"name":"2-m","value":"3"},
{"name":"3-m","value":"5"}
]';
$jm = json_decode($json_m, true);
$ja = json_decode($json_a, true);
$javal = array_unique(array_column($ja, 'value'));
$is_exist = FALSE;
$dataadd =[];
foreach($jm as $i=> $rows ){
$is_exist = FALSE;
if(is_numeric(array_search($rows["value"], $javal))) {
$is_exist = TRUE;
}
$dataadd[] = array ( 'ID' => $i,
'NAME' => $rows["value"],
'STATUS' => $is_exist
);
}
print_r($dataadd);

You could make your life easier by extracting all the value values from $ja using array_column; you can then search that using in_array. You can then iterate $jm using array_map to produce an array of $dataadd values:
$ja_values = array_column($ja, 'value');
$dataadd = array_map(fn ($arr, $idx) => array('ID' => $idx, 'NAME' => $arr['value'], 'STATUS' => in_array($arr['value'], $ja_values)), $jm, array_keys($jm));
var_export($dataadd);
Output (for your sample data):
array (
0 =>
array (
'ID' => 0,
'NAME' => '1',
'STATUS' => true,
),
1 =>
array (
'ID' => 1,
'NAME' => '2',
'STATUS' => false,
),
2 =>
array (
'ID' => 2,
'NAME' => '3',
'STATUS' => true,
),
3 =>
array (
'ID' => 3,
'NAME' => '4',
'STATUS' => false,
),
4 =>
array (
'ID' => 4,
'NAME' => '5',
'STATUS' => true,
),
)

Related

array_intersect different value

im using array_intersect for comparing 2 array
$myArray = array(
array(
'site_id' => 'S6407',
'tssr_id' => 'TSSRBOQ-200204-0145-59'
),
array(
'site_id' => 'S5910',
'tssr_id' => 'TSSRBOQ-200204-0145-8'
),
);
// $items_tssr is get from another variable
foreach ($items_tssr as $key => $value) {
$array_validate[] = array(
'site_id' => $value['site_id'],
'tssr_id' => $value['no_tssr_boq_site']
);
}
$result = array_map('unserialize',
array_intersect(
array_map('serialize', $myArray), array_map('serialize', $array_validate)));
// if there are same
if(array_key_exists(0,$result)){
echo 'process this';
}else{
echo 'dont process this';
}
my problem is, the original $myArray is more than 'site_id' and 'tssr_id'
$myArray_origin = array(
'site_id' => 'S6407',
'tssr_id' => 'TSSRBOQ-200204-0145-59'
'site_name' => 'Site S6407',
'id_site_doc'=> '127361,
'implementation_id' => 'imp4121',
'status' => "implementation_created",
"endstate" => false
),
...
how do i process the $myArray_origin without throw away a few of the value? because $array_validate is only have 2 value 'site_id' and 'tssr_id'
You could make use of array_filter + in_array instead. This will only keep the entries whose site_id and tssr_id are present in one of array_validate's own entries:
$result = array_filter($myArray, function (array $entry) use ($array_validate): bool {
return in_array([
'site_id' => $entry['site_id'],
'tssr_id' => $entry['tssr_id']
], $array_validate, true);
});
Demo: https://3v4l.org/4Qhmr

How can I update the key start from one on the php?

My first array like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
My second array like this :
photo = array('cover1'=>'liverpool.jpg', 'cover2'=>'city.jpg');
My code like this :
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo))
$photo=null;
If I run : echo '<pre>';print_r($photo);echo '</pre>';, the result like this :
Array
(
[cover2] => city.jpg
)
I want the result like this :
Array
(
[cover1] => city.jpg
)
So if there is no cover1, the cover2 changed to be cover1
How can I do it?
You could re-index the keys like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$photo = array('cover1'=>'liverpool.jpg', 'cover2'=>'city.jpg');
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo)){
$photo = null;
} else {
$idx = 1 ;
foreach ($photo as $key => $value) {
unset($photo[$key]);
$photo['cover'.$idx++] = $value;
}
}
print_r($photo);
Outputs :
Array
(
[cover1] => city.jpg
)
I'm not sure about what you really need. Assuming you want to do that recursively, I hope this helps:
$label = 'cover';
$index = 1;
$a_keys = array_keys($photo);
$new_photo = [];
foreach($a_keys AS $k=>$v){
$new_photo[$label.$index] = $photo[$k];
$index++;
}
$photo = $new_photo;
It will rewrite your array with wanted naming style.

how to check whether 4 exist or not in array at 'id' key position

how to check whether 4 exist or not in array at id key position
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
)
The array you provided is not a valid multi-dimensional array. You need to add commas after each array in the array. Below i use array_column and in_array without using foreach
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),//add comma
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
),
);
$filtered = array_column($arr, 'id');//return the id column in this array
if(in_array(4, $filtered)){//check if 4 exists
echo '4 exists';
} else {
echo '4 does not exist';
}
?>
Quite simple, loop through the array and check if the value exists:
$value = 4;
$exists = false;
foreach($arr as $innerArr){
if($innerArr['id'] == $value){
$exists = true;
break;
}
}
If $exists is now true, the value exists within the array.
Try this one, and let me know if you face any problem.
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
foreach ($arr as $key => $value) {
if (in_array("4", $value))
{
$sub_index = $value['id'];
echo "Match found at $sub_index";
break;
}
}
Just gotta loop through your array and check existence through in_array() function.
you need something like this
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
$exists_flag = false;
foreach($arr as $inside_arr)
{
if($inside_arr['other_data'] == 4) {
$exists_flag = true;
break;
}
}
print($exists_flag);
Hope this helps!
As it stand, your array is wrong, you need to separate multi array with commas, you need to not that in_array() will not work with multi array, however you may create a recursive function that will check a provided key does exists or not in an array try code below, hope it helps ,
<?php
$arr = array(
array(
'id' => 1,
'other_data' => 'ganesh'
),
array(
'id' => 2,
'other_data' => 'ramesh'
),
array(
'id' => 3,
'other_data' => '4'
)
);
function search_items($search_value, $array)
{
foreach ($array as $item) {
if (($item == $search_value) || (is_array($item) && search_items($search_value, $item))) {
return true;
}
}
return false;
}
echo search_items("4", $arr) ? 'item found' : 'item not found';
?>
$result = array_search(4, array_column($arr, 'id'));
If we split this into steps then it would be the following:
$allColumnsNamedId = array_column($arr, 'id'); // find all columns with key 'id'
$resultBoolean = array_search(4, $allColumnsNamedId); //search the array for value 4
if($resultBoolean) {
echo 'Exists';
} else {
echo 'Does not exist';
}

Find array elements that have a certain key-name prefix

I have an associative array with lots of elements and want to get a list of all elements that have a key name with a certain prefix.
Example:
$arr = array(
'store:key' => 1,
'user' => 'demo',
'store:foo' => 'bar',
'login' => true,
);
// this is where I need help with:
// the function should return only elements with a key that starts with "store:"
$res = list_values_by_key( $arr, 'store:' );
// Desired output:
$res = array(
'store:key' => 1,
'store:foo' => 'bar',
);
You could simply do :
$arr = array(
'store:key' => 1,
'user' => 'demo',
'store:foo' => 'bar',
'login' => true,
);
$arr2 = array();
foreach ($arr as $array => $value) {
if (strpos($array, 'store:') === 0) {
$arr2[$array] = $value;
}
}
var_dump($arr2);
Returns :
array (size=2)
'store:key' => int 1
'store:foo' => string 'bar' (length=3)
This should work for you:
Just grab all keys which starts with store: with preg_grep() from your array. And then do a simple array_intersect_key() call to get the intersect of both arrays.
<?php
$arr = array(
'store:key' => 1,
'user' => 'demo',
'store:foo' => 'bar',
'login' => true,
);
$result = array_intersect_key($arr, array_flip(preg_grep("/^store:/", array_keys($arr))));
print_r($result);
?>
output:
Array
(
[store:key] => 1
[store:foo] => bar
)
From php 5.6 you can use array_filter:
$return = array_filter($array, function ($e) {
return strpos($e, 'store:') === 0;
}, ARRAY_FILTER_USE_KEY);
var_dump($return);
for earlier versions, you can use
$return = array_intersect_key($array, array_flip(array_filter(array_keys($array), function ($e) {
return strpos($e, 'store:') === 0;
})));
Demo.

php flattening nested array

I have an array like this
$array:
{ name : xyz
version : Array[2]
{
0 : Array[2]
{
id : 1
batch : 1
}
1 : Array[2]
{
id : 2
batch : 2
}
}
}
How can I create an array like this:
$results[] =
name:xyz, version:0, id:1, batch:1
name:xyz, version:1, id:2, batch:2
I want an array where the common fields are repeated.
Do you mean:
$results = array();
$results[] = array('name' => 'xyz', 'version' => 0, 'id' => 1, 'batch' => 1);
$results[] = array('name' => 'xyz', 'version' => 1, 'id' => 1, 'batch' => 1);
Then access the first row by $results[0]['name']
Or second row by $results[1]['name']
EDIT
To convert from $array to $results, I have to assume your $array looks like this.
$array =
array('name' => 'xyz',
'version' => array(
0 => array(
'id' => 1,
'batch' => 1
),
1 => array(
'id' => 2,
'batch' => 2
)
)
);
then
$results = array();
$name = $array['name'];
foreach($array['version'] as $version => $idandbatch)
{
$results[] = array('name' => $name,
'version' => $version,
'id' => $idandbatch['id'],
'batch' => $idandbatch['batch']);
}
You can access the array
foreach($results as $values)
{
echo $values['name'];
echo $values['version'];
echo $values['id'];
echo $values['batch'];
}

Categories