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

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

Related

how to make array like this

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

Divide JSON into equal smaller parts using 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

How to change order of substrings inside a larger string?

This is fairly confusing, but I'll try to explain as best I can...
I've got a MYSQL table full of strings like this:
{3}12{2}3{5}52
{3}7{2}44
{3}15{2}2{4}132{5}52{6}22
{3}15{2}3{4}168{5}52
Each string is a combination of product options and option values. The numbers inside the { } are the option, for example {3} = Color. The number immediately following each { } number is that option's value, for example 12 = Blue. I've already got the PHP code that knows how to parse these strings and deliver the information correctly, with one exception: For reasons that are probably too convoluted to get into here, the order of the options needs to be 3,4,2,5,6. (To try to modify the rest of the system to accept the current order would be too monumental a task.) It's fine if a particular combination doesn't have all five options, for instance "{3}7{2}44" delivers the expected result. The problem is just with combinations that include option 2 AND option 4-- their order needs to be switched so that any combination that includes both options 2 and 4, the {4} and its corresponding value comes before the {2} and it's corresponding value.
I've tried bringing the column into Excel and using Text to Columns, splitting them up by the "{" and "}" characters and re-ordering the columns, but since not every string yields the same number of columns, the order gets messed up in other ways (like option 5 coming before option 2).
I've also experimented with using PHP to explode each string into an array (which I thought I could then re-sort) using "}" as the delimiter, but I had no luck with that either because then the numbers blend together in other ways that make them unusable.
TL;DR: I have a bunch of strings like the ones quoted above. In every string that contains both a "{2}" and a "{4}", the placement of both of those values needs to be switched, so that the {4} and the number that follows it comes before the {2} and the number that follows it. In other words:
{3}15{2}3{4}168{5}52
needs to become
{3}15{4}168{2}3{5}52
The closest I've been able to come to a solution, in pseudocode, would be something like:
for each string,
if "{4}" is present in this string AND "{2}" is present in this string,
take the "{4}" and every digit that follows it UNTIL you hit another "{" and store that substring as a variable, then remove it from the string.
then, insert that substring back into the string, at a position starting immediately before the "{2}".
I hope that makes some kind of sense...
Is there any way with PHP, Excel, Notepad++, regular expressions, etc., that I can do this? Any help would be insanely appreciated.
EDITED TO ADD: After several people posted solutions, which I tried, I realized that it would be crucial to mention that my host is running PHP 5.2.17, which doesn't seem to allow for usort with custom sorting. If I could upvote everyone's solution (all of which I tried in PHP Sandbox and all of which worked), I would, but my rep is too low.
How would something like this work for you. The first 9 lines just transform your string into an array with each element being an array of the option number and value. The Order establishes an order for the items to appear in and the last does a usort utilizing the order array for positions.
$str = "{3}15{2}2{4}132{5}52{6}22";
$matches = array();
preg_match_all('/\{([0-9]+)\}([0-9]+)/', $str, $matches);
array_shift($matches);
$options = array();
for($x = 0; $x < count($matches[0]); $x++){
$options[] = array($matches[0][$x], $matches[1][$x]);
}
$order = [3,4,2,5,6];
usort($options, function($a, $b) use ($order) {
return array_search($a[0], $order) - array_search($b[0], $order);
});
To get you data back into the required format you would just
$str = "";
foreach($options as $opt){
$str.="{".$opt[0]."}".$opt[1];
}
On of the bonuses here is that when you add a new options type inserting adjusting the order is just a matter of inserting the option number in the correct position of the $order array.
First of all, those options should probably be in a separate table. You're breaking all kinds of normalization rules stuffing those things into a string like that.
But if you really want to parse that out in php, split the string into a key=>value array with something like this:
$options = [];
$pairs = explode('{', $option_string);
foreach($pairs as $pair) {
list($key,$value) = explode('}', $pair);
$options[$key] = $value;
}
I think this will give you:
$options[3]=15;
$options[2]=3;
$options[4]=168;
$options[5]=52;
Another option would be to use some sort of existing serialization (either serialize() or json_encode() in php) instead of rolling your own:
$options_string = json_encode($options);
// store $options_string in db
then
// get $options_string from db
$options = json_decode($options_string);
Here's a neat solution:
$order = array(3, 4, 2, 5, 6);
$string = '{3}15{2}3{4}168{5}52';
$split = preg_split('#\b(?={)#', $string);
usort($split, function($a, $b) use ($order) {
$a = array_search(preg_replace('#^{(\d+)}\d+$#', '$1', $a), $order);
$b = array_search(preg_replace('#^{(\d+)}\d+$#', '$1', $b), $order);
return $a - $b;
});
$split = implode('', $split);
var_dump($split);

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

split and store into list with an array variable in php

I have a number that is get from a web page, such that
$number=12-34-33-87-54-................ and so on.
$number may have two numbers like $number=12-34
or
it may have 3 numbers like $number=12-34-33
or
it may have more numbers like $number=12-34-33-87-54-.......... and so on.
I want to split it by '-' and want to store in an array.
like array(12,34,33,.....)
I used the code given below but it doesn't work.
<?php
$a=array();
list($a)=split('-',$number);
foreach($a as $v)
{
echo $v;
}
?>
Plz tell me how can i split this?
$parts = explode('-',$number);
Although split() is depracated, explode will do the trick for you
<?php
$a=explode('-',$number);
foreach($a as $v)
{
echo $v;
}
?>
It assumes that a , is the default, so you can use it on a CSV without having to specify.
explode will return this array without any interfere from your side
$returnedArray = explode('-',$number);
this should work fine for you
Php explode is what you need here.
$arrayOfTokens = explode('-',$number);
explode returns an array of string, as stated in the documentation provided.

Categories