Randomly select item from JSON in PHP - php

I have a JSON string like this :
[{"Format":"I25","Content":"172284201241"}, {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]
and I just want to select one of these items randomly,for example :
{"Format":"I25","Content":"40124139"}
How can I do this with PHP?

That string looks a lot like JSON, so decode it into an array.
$array = json_decode($string, true);
Then, pick a random index:
$one_item = $array[rand(0, count($array) - 1)];
and finally convert back to JSON:
$one_item_string = json_encode($one_item);
echo $one_item_string;

If you need the array element as PHP assoc array use:
$string = '[{"Format":"I25","Content":"172284201241"}, {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]';
$result = array_rand(json_decode($string, true));
If you want the string encode it back:
$result = json_encode(array_rand(json_decode($string, true)));

First, convert the json to a PHP array, and then randomly pick an element from the array:
$json = '[{"Format":"I25","Content":"172284201241"}, {"Format":"I25","Content":"40124139"},
{"Format":"I25","Content":"20197086185689"},
{"Format":"I25","Content":"10215887"},
{"Format":"I25","Content":"702666712272"},
{"Format":"QRCODE","Content":"3"}]';
$arr = json_decode($json, true);
$element = $arr[mt_rand(0, count($arr) - 1)];
// optionally convert back to json
$json = json_encode($element);

Related

Convert a string structured as a Multidimensional Array to array

I have this string:
array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));
Stored in $_POST['data']
The string Im receiving is via.load` function where the structure of the string is constructed like so.
I would like to convert it to a multidimensional array via php so I can loop through it easily
So far I`ve reached a workaround by modifying both the string and the method.
Now my string looks like this :
1,name1,1,0,|2,name2,0,1,|3,name3,0,1,|4,name4,1,1,|5,name5,1,0,|
And the method is this
$data2 = $_POST['data2']; /// get data
$data2 = substr_replace($data2 ,"", -2); // eliminate ,|
$data2 = $data2."|"; // add |
$one=explode("|",$data2); // create multidimensional array
$array = array();
foreach ($one as $item){
$array[] = explode(",",$item);
}
I can keep this solution but I would like to know if there is another way of doing it as first requested
There is a better and simple way. You just need to use a foreach loop inside foreach loop.
$data = array(
array('1','name1','1','0'),
array('2','name2','0','1'),
array('3','name3','0','1'),
array('4','name4','1','1'),
array('5','name5','1','0')
);
foreach( $data as $d ) {
foreach( $d as $value ) {
echo $value;
echo '<br />';
}
}
You can check the online Demo
To parse your original string you can use eval()
$string = 'array(array('1','name1','1','0'),array('2','name2','0','1'),array('3','name3','0','1'),array('4','name4','1','1'),array('5','name5','1','0'));';
eval('$array = '.$string);
But eval can/should be disabled on the server, because it comes with security issues.
What i would do is to use JSON, where you would POST the json encoding it with:
json_ecnode( $my_array );
and then decoding it:
$array = json_decode( $_POST['data'], true );

How to convert strings to 2D array in php?

I have 2 strings which returns me the url and status from a curl call. I want to combine these two strings and create an array so that I can convert back to json object to fetch it in the twig.
I have tried using the explode() and the array() function.
$url =
"'http://www.testsite.com','http://www.google.org','http://www.fb.net'";
$status = 200,300,404;
var testArray = array($url,$status);
I want to make my array look like :
testArray[0][$url] = http://www.testsite.com and
testArray[0][status] = 200
Explode both strings, then loop over them and push an associative array with the values onto the result array.
$testArray = [];
$url_array = explode(',', $url);
$status_array = explode(',', $status);
foreach ($url_array as $i => $u) {
$u = trim($u, "'"); // remove surrounding quotes
$s = $status[$i];
$testArray[] = ['url' => $u, 'status' => $s];
}

PHP changing array format

I'm trying to change an array format from this
{"updated":"2016-01-28 02:00:02","rate":"0.1898"}
to this
[2016-01-28 02:00 , 0.1898]
I'm getting the first array format from a MySQL query and need to convert to the second format to use in a line chart.
$newVal = array();
foreach ($dbresult as $key => $value) {
$newVal[] = json_encode(array_values($value));
}
echo implode(",", $newVal);
With this new code block i get this format
["2016-01-28 02:00" , "0.1898"]
But still need to get rid of the double quotes, any ideas?
$json = '[{"updated":"2016-01-28 02:00:02","rate":"0.1898"}]';
echo json_encode(array_map(function ($data) {
return [$data->updated, $data->rate];
}, json_decode($json)));
In other words:
JSON-decode it
loop through it
create a new array with updated in the first index and rate in the second
JSON-encode it again
Step 3 is necessary since JSON objects don't guarantee any particular order, so relying on the decoded order of the keys is not reliable; and it also guarantees you get the data you want even if you add more keys to your objects.
Try this code
$string = ' {"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$array = json_decode($string, true);
$str = json_encode(array_values($array));
echo str_replace('"', '', $str);
you should try this
$str ='{"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$data=json_decode($str);
echo '<pre>';
echo 'json decode it returns ojbects<br>';
print_r($data);
echo 'convert object into array<br>';
$data=(array)$data;
print_r($data);
echo 'Your Output<br>';
echo json_encode(array_values($data));

Transforming array into json with PHP

I have this array
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions']['name'] = 'blur';
$params_array['functions']['params']['radius'] = '0.0';
$params_array['functions']['params']['sigma'] = '2.0';
$params_array['functions']['save']['image_identifier'] = 'MY_CLIENT_ID';
I need to transform it into json.
So I am doing this:
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES);
The result is
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}}
but, the receiver API of that json wants it to be formed slightly different, like this:
{"application_id":"xxx","v":1.2,"src":"http://www.google.com/logos/2011/yokoyama11-hp.jpg","functions":[{"name":"blur","params":{"radius":"0.0","sigma":"2.0"},"save":{"image_identifier":"MY_CLIENT_ID"}}]}
The difference: after "functions": there is this bracket [, and it's closed at the end.
PHP somehow does not create the json with this bracket.
How can I get PHP to create the json with those brackets?
The receiver API is http://www.blitline.com/docs/quickstart
You should prepare your structure this way:
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$params_array['functions'][0]['name'] = 'blur';
$params_array['functions'][0]['params']['radius'] = '0.0';
$params_array['functions'][0]['params']['sigma'] = '2.0';
$params_array['functions'][0]['save']['image_identifier'] = 'MY_CLIENT_ID';
(Making functions to a number indexed array.)
So receiver expects functions to be array objects, but you pass single object instead. Change $params_array['functions']['name'] to $params_array['functions'][$functionIndex]['name']
Try this
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['v'] = 1.20;
$params_array['src'] = 'http://www.google.com/logos/2011/yokoyama11-hp.jpg';
$function_array['name'] = 'blur';
$function_array['params']['radius'] = '0.0';
$function_array['params']['sigma'] = '2.0';
$function_array['save']['image_identifier'] = 'MY_CLIENT_ID';
$params_array['functions'] = array($function_array);
Reason:
JSON_ENCODE will treat an Array as JSON OBJECT if it is like Key=>Value
and it will treat as json array if it is index based like [0] => value
Alright, run this example then you'll know how to achieve it.
$params_array = array();
$params_array['application_id'] = 'xxxxxxxxx';
$params_array['another_array'] = array("A","B","C");
echo json_encode($params_array );
Result: {"application_id":"xxxxxxxxx","another_array":["A","B","C"]}
You can try to use the flag JSON_FORCE_OBJECT if you have PHP 5.4.0 or later :
$json = json_encode($params_array,JSON_UNESCAPED_SLASHES + JSON_FORCE_OBJECT);

From one string to two, with filter between string

I have this string:
[{"position":"1d","number":10,"nb_plot1":12,"max_actions":3}
{"position":"2d","number":7,"nb_plot1":15,"max_actions":30}
{"position":"3d","number":100,"nb_plot1":2,"max_actions":5}]
and i need to obtain two different string with different format like this:
for numbers:
[10,7,100]
for positions:
['1d','2d','3d']
and cut unnecesarry strings.
I'm a noob sorry.
Decode the string in a array with json_decode.
Iterate over this array and build new arrays for numbers and position.
Encode the arrays.
In code:
$arr = json_decode($string);
$numbers = array();
$positions = array();
foreach($arr as $a)
{
$numbers[] = (int)$a->number;
$positions[] = $a->position;
}
$number_string = json_encode($numbers);
$position_string = json_encode($positions);

Categories