I need to merge/join multiple json string that contains arrays (which also need to be merged) but I don't know what is the best way to achieve this :
Initial array of json strings (called $rrDatas in my example below):
Array
(
[0] => {"asset":[1],"person":[1]}
[1] => {"asset":[2]}
)
Expected result :
{"asset":[1,2],"person":[1]}
The main difficulty is that the number of arrays is undefined (my example is made with 2 arrays but it could be 3,4 etc.). The second difficulty is that there can be multiple properties (like "asset", "person" etc. however always arrays). These possible properties are known but are many so it would be better if the algorithm is dynamic.
What I am able to do at the moment :
$mergedAssets['asset'] = [];
foreach ($rrDatas as $rrData)
{
$rrDataJson = \GuzzleHttp\json_decode($rrData, true);
$mergedAssets['asset'] = array_merge($mergedAssets['asset'],$rrDataJson['asset']);
}
$result = \GuzzleHttp\json_encode($mergedAssets, true);
Result :
{"asset":[1,2]}
This works well but this is not dynamic, should I duplicate this part for each possible properties (i.e. "person", etc.) ?
Thanks,
Guillaume
Edit : Brett Gregson's and krylov123's answers below helped me build my own solution which is a mix between both suggestion:
$mergedJson = [];
foreach ($rrDatas as $rrData)
{
$rrDataJson = \GuzzleHttp\json_decode($rrData, true);
foreach(array_keys($rrDataJson) as $property)
{
$mergedJson[$property] = array_merge($mergedJson[$property] ?? [], $rrDataJson[$property]);
}
}
return \GuzzleHttp\json_encode($mergedJson, true);
Find below a better example :
$rrDatas = Array (
[0] => {"asset":[1,2],"person":[1],"passive":[1]}
[1] => {"asset":[3],"charge":[1],"passive":[2]}
)
Which must result in :
{"asset":[1,2,3],"person":[1],"passive":[1,2],"charge":[1]}
Edit 2 : I have just tried Progrock's solution and it seems to work perfectly as well : https://3v4l.org/7hSqi
You can use something like:
$output = []; // Prepare empty output
foreach($rrDatas as $inner){
foreach($inner as $key => $value){
$output[$key][] = $value;
}
}
echo json_encode($output); // {"asset":[1,2],"person":[1]}
Which should give you the desired output. This should work regardless of the keys within the individual arrays and even with empty arrays.
Working example here
Another example with more arrays and more keys and empty arrays
<?php
$array =
[
'{"asset":[1],"person":[1]}',
'{"asset":[2]}',
];
$array = array_map(function($v) { return json_decode($v, true);}, $array);
$merged = array_merge_recursive(...$array);
print json_encode($merged);
Output:
{"asset":[1,2],"person":[1]}
You need to use foreach ($array as $key => $value) iteration, to be able to dynamicaly use keys of your json array (e.g. "asset" and "person").
Solution:
$mergedAssets['asset'] = [];
foreach ($rrDatas as $key => $value)
{
$rrDataJson = \GuzzleHttp\json_decode($value, true);
$mergedAssets[$key] = array_merge($mergedAssets[$key],$rrDataJson[$key]);
}
$result = \GuzzleHttp\json_encode($mergedAssets, true);
Related
I'm trying two combine two arrays based on the values names.
Here what I'm trying to do :
$array1 = ("fifa21","pes21","halflife2","carma2");
$array2 = ("fifa21_cover","pes21_cover","halflife2_cover");
I want to loop through both arrays and if value from array1 match value from array 2 it will list both values like this :
fifa21 - fifa21_cover
pes21 - pes21_cover
halflife2 - halflife2_cover
carma2 - default_cover
if not find anything in the array2, a default cover will be used.
Note: the arrays will be filled dynamically based in a scanDir (two different folders search) and the arrays can be sorted differently than shown in the example above.
This code will loop through array1 and check to see if the item cover exists in array2, if it does then it will echo out in the format you wanted.
$array1 = array("fifa21","pes21","halflife2","carma2");
$array2 = array("fifa21_cover","pes21_cover","halflife2_cover");
foreach ($array1 as $item) {
if (in_array($item."_cover", $array2)) {
echo "<p>".$item." - ".$item."_cover</p>\n";
} else {
// use default cover...
}
}
(because it is lunch time and I need to write some code)
Given two arrays:
$array1 = ["fifa21", "pes21", "halflife2", "carma2"];
$array2 = ["fifa21_cover", "pes21_cover", "halflife2_cover"];
A function such as this can walk through and look for items that start with those values:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$items = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key));
if (count($items) === 1) {
$output[$key] = reset($items);
return;
}
if (count($items) === 0) {
$output[$key] = 'default_cover';
return;
}
throw new RuntimeException('More than one item found starting with key ' . $key);
}
);
return $output;
}
When called as:
print_r(merge_arrays($array1, $array2));
It will output:
(
[fifa21] => fifa21_cover
[pes21] => pes21_cover
[halflife2] => halflife2_cover
[carma2] => default_cover
)
For your use-case, it might be overly complicated when compared to a for loop, but it does the job.
Another version that more-blindly assumes only a one-to-one match could use the ?? operator for a null check, although I wouldn't recommend this. The more terse and compact that code looks, the more I find that it is usually very hard to reason about, especially in the future:
function merge_arrays(array $array1, array $array2): array
{
$output = [];
array_walk(
$array1,
static function ($key) use ($array2, &$output) {
$output[$key] = array_filter($array2, static fn($f) => 0 === mb_strpos($f, $key))[0] ?? 'default_cover';
}
);
return $output;
}
All code snipping provided works, however if the array values have extension it always assumes the default cover. I can figure it how using my code by removing the extension for compare purpose, and then I add it back.
Inside my loop I use this :
$keyvaluetemp = substr($keyvalue, 0, strrpos($keyvalue, "."));
the above it inside my first ForEach (where I check the first array), and then in the covers array I remove the "_cover" by nothing :
$keyvalue2temp = (str_replace("_cover", "",$keyvalue2));
then I use the following code inside the second ForEach to add the data to a DB:
// if fantart match the game file name so we associate it to the game and save to the DB
if ( stripos ( $keyvalue2temp , $keyvaluetemp ) !== FALSE )
{
$sql = "UPDATE listgames SET FanArt='$keyvalue2' WHERE Name='$keyvalue'";
$con->exec($sql);
}
// if fanart is empty we add a default picture
$checkifempty = "SELECT `FanArt` FROM `listgames` WHERE `Name` = '$keyvalue'";
$runsql = $con->query($checkifempty);
$row = $runsql->fetch(PDO::FETCH_ASSOC);
$fanartkey = $row['FanArt'];
if($fanartkey == '')
{
$sql = "UPDATE listgames SET FanArt='nopic.JPG' WHERE Name='$keyvalue'";
$con->exec($sql);
}
Later in my code I print the results from the DB. I don't know if this is the best approach, however it does exactly what I want :)
I need to get values of array through a loop with dynamic vars.
I can't understand why the "echo" doesn’t display any result for "$TAB['b']".
Do you know why ?
The test with error message : https://3v4l.org/Fp3GT
$TAB_a = "aaaaa";
$TAB['b'] = "bbbbb";
$TAB['b']['c'] = "ccccc";
$TAB_paths = ["_a", "['b']", "['b']['c']"];
foreach ($TAB_paths as $key => $value) {
echo "\n\n\${'TAB'.$value} : "; print_r(${'TAB'.$value});
}
You are treating the array access characters as if they are part of the variable name. They are not.
So if you have an array $TAB = array('b' => 'something');, the variable name is $TAB. When you do ${'TAB'.$value}, you're looking for a variable that's actually named $TAB['b'], which you don't have.
Since you say that you just want to be able to access array indexes dynamically based on the values in another array, you just put the indexes alone (without the array access characters) in the other array.
$TAB['b'] = 'bbbbbb';
$TAB['c'] = 'cccccc';
$TAB_paths = array('b', 'c');
foreach ($TAB_paths as $key => $value) {
echo "\n\n".'$TAB['."'$value'".'] : ' . $TAB[$value];
}
Output:
$TAB['b'] : bbbbbb
$TAB['c'] : cccccc
DEMO
It's unclear what you're trying to do, although you need to include $TAB_all in $TAB_paths:
$TAB_paths = [$TAB_all['a'], $TAB_all['aside']['nav']];
Result:
${TAB_all.aaaaa} : ${TAB_all.bbbbb} :
Not certain what you're needing. My guess you need to merge two arrays into one. Easiest solution is to use the array_merge function.
$TAB_paths = array_merge($TAB_a1, $TAB_a2);
You can define the variable first
foreach ($TAB_all as $key => $value) {
${"TAB_all" . $key} = $value;
}
Now Explore the result:
foreach ($TAB_all as $key => $value) {
print_r(${"TAB_all" . $key});
}
I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!
In my project i'm split an array index value based on regex value. but when i want merge all array together the merge function doesn't merge.
Here is my code sample.
$testarray=array();
$merge_array=array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
print_r(array_merge($merge_array,$testarray));
}
The print_r show this result.
Array ( [0] => Admin [1] => Manager ) Array ( [0] => User [1] => Test )
You just merge arrays, but don't assign results to any variable, proper code is:
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
// here you add $testarray values to
// `$merge_array` on each iteration
$merge_array = array_merge($merge_array,$testarray);
}
// print result array after loop
print_r($merge_array);
The Laravel framework has nothing to do with your issue. You're using PHP's standard functions.
The array_merge function doesn't modify the array you provide to it but provides the resulting array as its output. So you should assign array_merge's result to $merge_array.
Please try the following code:
$testarray = array();
$merge_array = array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray = preg_split("/[##%$|:\s,]+/",$value);
}
$merge_array = array_merge($merge_array, $testarray);
}
print_r($merge_array);
You seem to think wrong.
print_r(array_merge($merge_array,$testarray));
The above line is in "foreach" loop.
In that case, to get a merged result, you should do like the followings;
$merge_array = array_merge($merge_array,$testarray)
In your code, $merge_array remains empty, so you see the current result.
Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)