Divide JSON into equal smaller parts using php - php

I have a JSON containing lets say 14 elements.
How can I divide it in smaller JSONs of lets say 2 or 3 elements each.

Do not know what your exact json is, but this will serve as an example:
<?php
$jsonExample = '["a","b","c","d","e","f","g","h","i"]' ;
$arrResult = json_decode($jsonExample,true);
$output = array_chunk($arrResult,3);
var_dump($output);
?>
demo:http://codepad.org/aYBg19DB

I would recommend using json_decode() and array_chunk().
http://php.net/manual/en/function.array-chunk.php
http://php.net/manual/en/function.json-decode.php

Related

PHP - Creating an array from a string given from an API

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);
?>

Converting multiple strings into JSON arrays

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.

spiltting an array into n arrays and accessing individual arrays in php

I have an array of 1000 emails.
And I want to split the array into n arrays having 45 emails in each array.
I want to separately access the splitted arrays.
How can we implement using php. I have also tried array_splice() function in php, but it returns splitted arrays, but I unable to access the splitted array.
You could use array_chunk() in this case to get batches of those emails:
$emails = array('email1', 'email2', ..... 'email1000');
// 45 each batch
$batch_emails = array_chunk($emails, 45);
foreach($batch_emails as $batch) {
print_r($batch);
}
// or explicitly get batch/group 5
print_r($batch_emails[4]);
try this -
$f = array_chunk($yourArray, 45);
var_dump($f);
Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

Array_diff not taking in arguments

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);

Get data from a string and return it as JSON in PHP

NOTE : This is for a PHP script !
So I've been working on a program but I right now I am stuck because I can't split the data right.
I have a list with numbers just like this :
50.0.1 581 50.0.2 545 50.0.3 541 50.0.4 18 50.0.5 2 50.0.6 33 50.0.7 1 [...]
I have add that information into an ARRAY or JSON format (preferable JSON).
The main data looks like this (we take groups): 50.0.1 581 so basically I have to split 50.0.1 from 581 add it to JSON/ARRAY and then move to the next group that in our case is 50.0.2 545. (and so on)
Example JSON:
{"result": {
"50.0.1": "581",
"50.0.2": "545"
}}
Note : First value will always have the same format : [0-9]{2}.[0-9].[0-9] (ex : 50.0.1)
However, the second value can be 1 to 4 digit long : [0-9]{1,4}.
I am sorry if I did not make myself clear - it is quite hard to explain. Will add more example if required !
Thank you very much !
simply explode on the spaces, e.g.
$arr = explode(' ', $your_string);
then build a new array using each pair of elements:
$newarr = array();
for ($i = 0; $i < count($arr); $i += 2) { // note the += 2
$newarr[$arr[$i]] = $arr[$i+1];
}
echo json_encode($newarr);
note that this will probably trash things if any of those "key" values are duplicates.
My own working solution : /([.\d])\t(\d)/ . Will output 3 arrays. Simple combine second with third and I got what I want.
Another way is to use array_chunk() after explode(), and then access values in JS as item[0] and item[1] for each pair.

Categories