I am trying to get the difference of two files:
$first = file('lalala.json');
$second = file('alabala.json');
//print_r($first);
//print_r($second);
$first_result = array_diff($first[0], $second[0]);
//$second_result = array_diff($second, $first);
print_r($first_result);
//print_r($second_result);
The content of lalala.json is:
`[{"name":"Tim Pearson","id":"17118"},{"name":"Ashley Danchen Chen","id":"504829084"},{"name":"Foisor Veronica","id":"100005485446135"}]`
while the content of alabala.json is
`[{"name":"Tim Pearson","id":"17118"},{"name":"Foisor Veronica","id":"100005485446135"}]`
However the problem is that I get an error, because the content will not be recognised as an array (the error is Argument #1 is not an array). If I do array_diff($first, $second) the output will be the content of $first which is
Array ( [0] => [{"name":"Tim Pearson","id":"17118"},{"name":"Ashley Danchen Chen","id":"504829084"},{"name":"Foisor Veronica","id":"100005485446135"}] )
How should I handle this?
You need to convert the JSON objects to arrays first and then find the difference between the two arrays. To convert a JSON string into an array use json_decode() with true as second parameter:
$firstArray = json_decode($first, true);
If you leave the second parameter out, $firstArray would be an object, that is an instance of stdClass.
But first you'd need the content of the file as a string, so better use file_get_contents():
$first = file_get_contents('lalala.json');
Update:
Even when you've converted the JSON strings properly into array, you'll still have a problem, as array_diff() only works with one dimensional arrays, as it's mentioned in the Notes section of the documentation. To be able to use in on multidimensional arrays, have a look at this comment to the documentation.
You probably mean
$first = json_decode(file_get_contents('lalala.json'), true);
$second = json_decode(file_get_contents('alabala.json'), true);
Related
I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}
I have a string containing that is being returned from an API which is dynamic, an example of the string is below:
[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]
I cant really do anything with it like this so i would like to split it into 2 arrays, one for the first number and one for the second, like so:
Array1
1473261033000
1473312464000
1473313206000
1473313505000
1473313805000
1473314105000
Array2
3.7933
2.0295
2.0844
1.4888
1.3003
1.1164
Would someone help me out on how i could go about this? its driving me nuts.
You need to first decode the JSON string into an array, then use array_column to extract the two arrays.
This will require PHP >=5.5, but if you require a lower version then you should be able to find a backwards compatible version of the function on the documentation page.
<?php
$str = '[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]';
$json = json_decode($str, true)[0];
$first = array_column($json, 0);
$second = array_column($json, 1);
print_r($first);
print_r($second);
See https://eval.in/637961 for a demo.
Well! json_decode() turns it to an array. Whether it's any use to you depends on what you want to do with the data really, doesn't it?
I'm wondering why you want to split it in two arrays. Isn't it easier to keep it in one?
<?php
$val = '[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]';
$myData = json_decode($val);
var_dump($myData);
?>
I read that array_merge will return NULL if you try to merge an empty array and any other array. That's not what I hope to do. I am trying to merge an array with a new array that is actually a slice of another array. ($i is an integer).
$forgotten = array_slice($matches, $i) ;
$leftOvers = array_merge($leftOvers, $forgotten);
The question is, what does array_slice return when the index is not found? If it can return null, should I do something like this:
$forgotten = array_slice($matches, $i) || array();
Also, is there any difference between using array_merge like this, and pushing $forgotten into leftOvers?
if you use array_merge over an empty array and another array it will return an array composed with the elements of the not empty array. If you try to merge two empty arrays it will return an empty array.
array_slice($matches, $i)
array_slice returns an array with all the elements of $matches with index greater or equal $i, if there are no such elements it will return an empty array.
Using array_push:
array_push($leftOvers, $forgotten)
$result will enqueue an array as a value the end of $leftOvers.
Always try to read the php man when you use a new php function, also you could get all these answers just trying to execute the functions in a test.php file.
I have multiple strings that looks like the following: 11-16, 16-12, 14-16
I will have multiple of these, and I need to store them in JSON. I need to store it in the following format:
[
{
"score_1": 11,
"score_2": 16
},
{
"score_1": 16,
"score_2": 12
},
{
"score_1": 14,
"score_2": 16
}
]
with score_1 being the first number, and score_2 being the second number. How will I be able to do this in PHP?
Thanks
First create an array. Next create an object, then explode the string on the hyphen and store the intval'd first and second number in the object. Push that object into your array. Repeat for as many strings as you have. Finally, use json_encode to get a JSON-encoded string.
$arr = [];
function addString($str, &$arr) {
$str = explode("-", $str);
$obj = new stdClass();
$obj->score_1 = intval($str[0]);
$obj->score_2 = intval($str[1]);
$arr[] = $obj;
}
addString("11-16", $arr);
addString("16-12", $arr);
echo json_encode($arr);
Output:
[{"score_1":11,"score_2":16},{"score_1":16,"score_2":12}]
Edit: Updated the above code to use intval as the OP has integers in his object in the expected output.
Two steps:
Convert the strings to the according data structure (e.g. array of stdClass objects).
Convert that data structure to JSON.
Note: Since you already know the output you want, you could parse that output to get an idea how its representation in PHP would look like, as a suggestion for the results of the first step.
I have an array, and when i echo it i get the following output;
Array[{"name":"Kat","age":"10"}]
Now, i need to add an additional filed into this; so finally it should appear as;
Array[{"message":"Success","name":"Kat","age":"10"}]
if $arr is my array, how am i going to append "message":"Success" ?
Sorry, i don't have any code to demonstrate my workings, i am stuck here. i would appreciate it if anyone can help me.
Your array content looks like JSON to me. But, if your array are actually just PHP arrays, then do:
$arr = array('name' => 'Kat', 'age' => '10');
$arr['message'] = 'Success';
If it is a JSON encoded array:
$arr = json_decode('{"name":"Kat","age":"10"}' , true)); //true decodes to an array and not a standard object
$arr['message'] = 'Success';
echo $arr;
//If you want it back in JSON
$json = json_encode($arr);
echo $json;
Like Waygood said if you want to add a value to the end of an array just use:
$array[] = $value; or $array['somekey'] = $somevalue;
However, if you need to add a value to the beginning of the array (like your example) you can use:
array_unshift($array, $value);
Alternatively, if you need to add a key and a value to the beginning you can simply make an array with the key => value pair and merge the two arrays like so:
$firstArray = array("message" => "Success");
$newArray = array_merge($firstArray, $secondArray);
For reference, here are the links to the php.net documentation:
array_unshift
array_merge
what about $arr["message"]="Success";?
To add a named field, you can just use this:
$array['message'] = 'Success';
To add a unnamed field, this is the way to do it:
$array[] = $value;
There are multiple ways of doing it.
PHP array functions
http://php.net/manual/en/function.array-push.php
http://php.net/manual/en/function.array-merge.php
The + operator
Or like others mentioned using $arg['var'] =
Just define "message":"Success" as another array and use push, merge or +
Also looks like you have it Json encoded. You will need to handle that as well.
The array functions only work with regular arrays, not encoded strings.
Try this:
$arr = array("name"=>"Kat","age"=>"10");
print_r($arr);
$arr = array_merge(array("message" => "Success"), $arr);
print_r($arr);