how to detect a duplicate element between two json object in php - php

i trying to detect a different element between 2 json objects like this;
//Json1
[
{"file":"arrowssss.png"},
{"file":"arrows.png"},
{"file":"logo.png"}
]
//Json1
[
{"file":"arrows.png"},
{"file":"logo.png"}
]
I need return Arrowsss.png.
Any Suggestion?

Try
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
$json1 = '[{"file":"arrowssss.png"},
{"file":"arrows.png"},
{"file":"logo.png"}]';
$json2 = '[{"file":"arrows.png"},
{"file":"logo.png"}]';
$array1 = flatten(json_decode($json1,true));
$array2 = flatten(json_decode($json2,true));
print_r(array_diff($array1,$array2));
Results :-
Array ( [0] => arrowssss.png )

$json1='[
{"file":"arrowssss.png"},
{"file":"arrows.png"},
{"file":"logo.png"}
]';
$json2 = '[
{"file":"arrows.png"},
{"file":"logo.png"}
]';
function getFile($key)
{
return isset($key['file']) ? $key['file'] : null;
}
$diff = array_diff(array_map('getFile', json_decode($json1, true)), array_map('getFile', json_decode($json2, true)));
print_r($diff);
Result:-
Array ( [0] => arrowssss.png )

Related

Convert flat array of string into associative array

I want to convert this array of string;
$arList = ["the","quick","brown","fox"];
into this format.
[
"the" => [
"quick" => [
"brown" => []
]
]
]
Sorry for not posting some code.
here is what I tried,
<?php
$arList = ["the","quick","brown","fox"];
$newList = [];
$pointer = $newList;
foreach($arList as $item) {
$pointer[$item] = [];
$pointer = &$newList[$item];
}
echo "<pre>";
print_r($newList);
echo "</pre>";
I found a solution from the net using the following code;
$result = array_reduce(array_reverse($arList), function($prevArray, $key){
return $prevArray ? [$key => $prevArray] : [$key];
}, null);

Creating multi dimensional array with array of keys

I want to create function which creates multidimensional array from parameter and second parameter should be saved as value here. Expected result is below:
Array
(
[first] => Array
(
[second] => Array
(
[last] => value
)
)
)
what I got so far :
$array = ['first', 'second', 'last'];
function multiArray($array, $newArray = [], $valueToSave)
{
if($array) {
$value = current( $array );
$key = array_search($value, $array);
unset( $array[ $key ] );
$newArray[$value] = [];
return multiArray( $array, $newArray, $valueToSave);
} else {
return $newArray;
}
}
Any tips, what should I change or do next ?
You can try this simplest one.
Try this code snippet here
$array = ['first', 'second', "third", "fourth",'last'];
$value = "someValue";
$result = array();
$count = count($array);
for($x=$count-1;$x>=0;$x--)
{
if($x==$count-1):
$result[$array[$x]]=$value;//setting value for last index
else:
$tempArray = $result;//storing value temporarily
$result = array();//creating empty array
$result[$array[$x]] = $tempArray;//overriting values.
endif;
}
print_r($result);

how to match a key value pair in a JSON

[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]
in the above JSON, how to get all the category which has type: 30days.
Expected Output as.
$categories = array{0=>30,1=>32,2=>33,3=>34,4=>37,4=>47}
You can use array_walk as
$json = '[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]';
$arr = json_decode($json,true);
$categories = array();
array_walk($arr,function($v,$k)use(&$categories,$arr){
if($v['type'] == "30 days"){
$categories = array_merge($categories,$v['category']);
}
});
Use this:
$json = '[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]';
$a = json_decode($json,true);
$categories = array();
foreach($a as $ar){
if($ar['type'] == '30 days'){
$categories = array_merge($categories,$ar['category']);
}
}
print_r($categories);
Output:
Array ( [0] => 30 [1] => 32 [2] => 33 [3] => 34 [4] => 37 [5] => 47 )
http://sandbox.onlinephpfunctions.com/code/ea84f8a5baf5c231b4e9427b3b79f16bbc075401
Just chain a bunch of transformation functions together:
$data =<<<JSON
[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]
JSON;
$data = json_decode($data, true);
$x = call_user_func_array('array_merge', array_column(array_filter($data, function($row) {
return $row['type'] == '30 days';
}), 'category'));
print_r($x);
See also: array_filter() array_column() call_user_func_array()

How to convert array to associative array?

This is my array format:
$data=["error.png","invoice_1.pdf","invoice2.png"];
But I want to this format:
$data=[{"file":"error.png"},{"file":"invoice_1.pdf"},{"file":"invoice2.png"}]
Thank you.
You should create a new array.
And loop through your existing array.
Its every element will be an array with a value from your array as value.
And key as the string file.
$arr = array();
foreach ($data as $elem) {
$arr[] = array('file' => $elem);
}
Try debugging if you get the correct array:
echo '<pre>';
print_r($arr);
echo '</pre>';
Lastly,
echo json_encode($arr);
exit;
Hope it works for you.
Use
$data = array_map(
function ($item) {
return array('file' => $item);
},
$data
);
to embed the values into arrays, or
$data = array_map(
function ($item) {
$x = new stdClass();
$x->file = $item;
return $x;
},
$data
);
to embed them into objects.
Or, better, use your own class instead of stdClass() and pass $item as argument to its constructor
$data = array_map(
function ($item) {
return new MyClass($item);
},
$data
);
$data = ["error.png", "invoice_1.pdf", "invoice2.png"];
$newarray = array();
foreach ($data as $val){
array_push($newarray, array("file" => $val));
}
print_r($newarray); //Array ( [0] => Array ( [file] => error.png ) [1] => Array ( [file] => invoice_1.pdf ) [2] => Array ( [file] => invoice2.png ) )
echo json_encode($newarray); // [{"file":"error.png"},{"file":"invoice_1.pdf"},{"file":"invoice2.png"}]
exit;
Just try this logic
$data = '["error.png","invoice_1.pdf","invoice2.png"]';
$data = json_decode($data);
$data = array_filter($data, function(&$item){return ($item = array('file' => $item));});
$data = json_encode($data);

How to show JSON data with Associate Array Key?

in the below code, i used simple $key,$value but i want to use that code with associate array key. Then how can i do? Please help.
<?php
function custom_table_page_display() {
$jsonData = '{ "User":"John", "Age":22, "Country":"India" }';
$phpArray = json_decode($jsonData);
$rows = array();
foreach($phpArray as $key => $value)
{
$rows[] = $key;
$value1[]=$value;
}
$header=$rows;
$value11[]=$value1;
$output = theme('table',array('header'=>$header,'rows' => $value11));
return $output;
}
?>
You need to use
$phpArray = json_decode($jsonData, true);
The second argument says whether to return an associative array or object for a JSON object. By default it returns an object.
You can replace your foreach loop with:
$rows = array_keys($phpArray);
$value1 = array_values($phpArray);
For the data you gave in the comment below, you would do:
$rows = array_keys($phpArray['Class'][0]);
$values = array_map('array_values', $phpArray['Class']);
$values will then be a 2-dimensional array of values:
[ [ "John", 22, "India" ],
[ "Sam", 23, "Argentina" ],
[ "John", 22, "Algeria" ]
]
DEMO

Categories