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.
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'd like to convert the following string to array
{"0":"7","1":"12","2":"14","3":"13"}
I tried str_replace'ing but this isn't a proper sollution by far.
Further I checked if php's unserialize() could do it but that was no luck either.
What is the best way to convert
{"0":"7","1":"12","2":"14","3":"13"}
To
7,12,14,13
Edit:
The complete script should compare 2 of these strings to check if one of the numbers are the same.
So let's say String A is:
7,12,14,13
And String B is
4,9,11,12,15
It should set a var to 'true' since 12 is found in both strings.
String A is formatted as above which needs to be unserialized
Thank you in Advance!
Looks like JSON to me.
Decode json with json_decode
parse all elements to an integer with intval
run implode on the array to convert it back to a string.
A quick one-liner would look like +/- this
implode(',', array_map("intval", json_decode('{"0":"7","1":"12","2":"14","3":"13"}', true)));
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.implode.php
Second problem
To know if any value appears in both string $A and string $B, array_intersect() can be used.
$var = count(array_intersect(explode(',', $A), explode(',' $B))) > 0;
or if $A and `$B are arrays
$var = count(array_intersect($A, $B)) > 0;
http://php.net/manual/en/function.array-intersect.php
You can use explode() function convert string to array.
$str={"0":"7","1":"12","2":"14","3":"13"}
$arr1=explode(",",$str);
$result=array();
foreach($arr1 as $substr)
{
$syn=explode(":"$substr);
$result[]=$syn[1];
}
print_r($result);
Your string look like JSON string. You can parse JSON string using json_decode in PHP. Then used implode function for get comma separated values.
$str = '{"0":"7","1":"12","2":"14","3":"13"}';
$final_str = implode(",",json_decode($str,true));
echo $final_str;
You can use json_decode, explode, implode functions
$string = '{"0":"7","1":"12","2":"14","3":"13"}';
$result_array = explode(",", implode(',', array_map("intval", json_decode($string, true))));
print_r($result_array);
Output:
Array ( [0] => 7 [1] => 12 [2] => 14 [3] => 13 )
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);
How do iterate through a deserialized json string? I can't get the right number of values right now it doesn't count right.
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
print Dumper($deserialize);
$VAR1 = [
'ab',
'cc',
'de',
'aer',
'ffe',
'cer',
'dad',
'efef',
'afaf',
'ege',
'grsc',
'cegg',
'cegg',
'cegg/aaa.html',
'eggt',
'ttt'
];
print length($deserialize);
13 ?? it should say 16
You are getting back an array reference not an array. You need to dereference the value.
my #array = #$deserialize; # or #{ $deserialize }
print scalar #array;
Moreover, if you want to iterate over the array you can just use for
for (#$deserialize) {
# do stuff
You are actually working with reference to the results. Since JSON can contain all sorts of different results, decode_json won't return a list specifically.
So you need to dereference the variable that you have: $deserialize
Additionally, you don't really want to be using the length function. If you print the integer value (or scalar value) of an array, it will return it's size.
So here's what you want:
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
print scalar (#{$deserialize});
That will print the size of the array.
If you want to just start by working with an array you can do:
my $list = request("http://localhost/getjson.php");
my $deserialize = from_json( $list );
my #json_array = #{$deserialize});
print scalar (#json_array);
From perldoc -f length:
This function cannot be used on an entire array or hash to find
out how many elements these have. For that, use "scalar
#array" and "scalar keys %hash", respectively.
You cannot use length to find out the size of an array. To do that, use the advice above.
Your bug gives you a false value because you are taking the length of the array reference, which in string context will be something like ARRAY(0x22d0a88), which in your case seemed to be 13 characters long. E.g. the equivalent of:
print length "ARRAY(0x22d0a88)";
As a curious side note, if you would do length(#array), it will actually return the length of the length of the array. E.g. an array of size 16 would return 2, because the string "16" is two characters long.