Convert raw string that contain "Array" to PHP Array or JSON - php

I have string that look like Array that fetched from other webservice like this
[
[
[189, 'Brazil Serie A', 0, ''],
[
[1053230, 'Flamengo', 'Atletico Goianiense', '1.196', 10, '07/02/2012 04:30', 0, 9, 1, 0, '', 0]
],
[0, [
[10770901, 0, 5000.00],
[1, 17988654, '-0.78', '0.70', '1.0', 1],
[3, 17965783, '0.97', '0.93', '2.5-3'],
[7, 17965787, '-0.89', '0.77', '0.50', 1],
[9, 17965789, '0.70', '-0.82', '1.0']
]]
],
[, , [0, [
[10748028, 0, 3000.00],
[1, 17965781, '0.85', '-0.93', '0.5-1', 1],
[3, 17988655, '0.79', '-0.89', '2.50']
]]]
]
Is it possible to parsing to PHP Array or convert to JSON ?

As ctrahey noted, the single quotes need to be swapped to double quotes to be valid JSON. The commas without anything preceding them also have to go.
// quote to double quote
$input = str_replace("'", '"', $input);
// remove empty commas
$input = preg_replace('/,\s*,/', ',', $input);
$input = preg_replace('/\[\s*,/', '[', $input);
$output = json_decode($input));
I've tried to keep it simple and build a little flexibility in.

Um, at first glance... if you convert your single quotes to double quotes, you already have JSON. I switched about half and it was validating okay through that point.
See the spec for details, but this is essentially just a bunch of arrays. The double-quote requirement for strings is clearly stated there, and the rest looks okay.

Related

PHP Convert multidimensional array to a string (LITERALLY)

I have a PHP multidimensional array that looks like this:
[[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]]
(Those numbers are stored as strings, not int)
What I want is to convert this multidimensional array to a string that teorically is stored like this:
$converted = "[[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]]";
Literally all the array in one string
currently I have the array stored in a variable named $array
Use json_encode,
$array = [[1,45],[2,23],[3,37],[4,51],[5,18],[6,32],[7,29],[8,45],[9,37],[10,50]];
echo json_encode($array);
And if your numbers is string, you can convert them to int before json_encode,
$array = [["1", "45"], ["2", "23"], [3, 37], [4, 51], [5, 18], [6, 32], [7, 29], [8, 45], [9, 37], [10, 50]];
echo json_encode(array_map(function ($subArray) {
return array_map(function ($number) {
return intval($number);
}, $subArray);
}, $array));

How to remove outer quotes from square bracket in array value

I have this array and I need to use it in Charts
in data index I have this value [1,9] and it's coming form the comma split explode function without any quotes around it.
$main_arr = array(
"label" => 'Total Clicks',
"data" => [$total_clicks],
"backgroundColor" => "rgba(255, 0, 0, 1)",
);
Then I use json_encode to turn the array into json format,
[{"label":"Total Clicks","data":["1, 9"],"backgroundColor":"rgba(255, 0, 0, 1)"}]
As you can see above there are double quotes in the square bracket, if I pass static value in the data index i.e [1, 9] it works fine. I tried regex, substring, rtrim etc but didn't work anyone.
Your help would be much appreciated!
You have several problems at once here. First of all your values are strings, and secondly you have an multiple values that you want to explode so you have singular values:
$total_clicks = '1, 9'; // value guessed based on unexpected output in question
$clickArray = explode(',', $total_clicks);
$clickArray = array_map('trim', $clickArray); // remove white spaces
$clickArray = array_map('intval', $clickArray); // cast everything to int
$main_arr = array(
"label" => 'Total Clicks',
"data" => $clickArray,
"backgroundColor" => "rgba(255, 0, 0, 1)",
);
echo json_encode($main_arr);
this outputs:
{"label":"Total Clicks","data":[1,9],"backgroundColor":"rgba(255, 0, 0, 1)"}
For a more sloppy approach you could even skip the line where I trim the whitespaces away, as casting to integer will do this implicitly, however I like to have a clean flow of handled data.
Converting string to array of ints:
$total_clicks = "1, 9";
print_r(array_map('intval', explode(', ', $total_clicks)));
Converting string to array of strings:
$total_clicks = "1, 9";
print_r(array_map('trim', explode(', ', $total_clicks)));

Array to string conversion - Validation rule for eloquent

I'm trying to validate a field using "in" and then passing an array befored defined. But when creating I get this error
"message": "Array to string conversion",
"exception": "ErrorException",
If I comment out the line where I use the validation, then works. So I'm pretty sure the problem is that.
I've seen another related posts, but they didn't work.
Thank you.
CONST ARRAY_EXAMPLES = [
'example1' => 0,
'example2' => 1,
'example3' => 2,
'example4' => 3,
'example5' => 4,
'example6' => 5,
];
protected $fillable = [
'array_example'
];
'array_example' => 'int|in:' .array_values(self::ARRAY_EXAMPLES)
When you concatenate two expressions in php both of them are casting to strings. But there is no any built in way to cast array to string. So you can't concatenate string and array here:
'int|in:' .array_values(self::ARRAY_EXAMPLES)
But you can convert array to string by implode:
'int|in:' . implode(',', self::ARRAY_EXAMPLES)

json_encode( json_encode (array) )

I'm trying to create a PHP script to generate JSON data for a jqplot bubble chart. The jqplot sample code requires data in the format
var arr = [
[45, 92, 1067, {label:"Alfa Romeo", color:'skyblue'}],
etc.
];
My script is along the lines of
while ...
array_push(
$arrBubble,
array(
11,
123,
1236,
json_encode(
array('label' => $car, 'color' => 'skyblue')
)
);
}
echo json_encode($arrBubble);
The problem is that the result is
[ [11, 123, 1236, "{\"label\":"VW", \"color\":\"skyblue\"}"] ]
The double json_encode has encoded the object(?) as a literal string.
What's the best way to work around this?
There is no reason to explicitly have a json_encode for one of the values inside the array. When you're using json_encode, it'll convert each level of the array as you expect.
var_dump(json_encode([
11,
123,
1236,
['label' => $car, 'color' => 'skyblue']
]));
Outputs the structure you want:
string(48) "[11,123,1236,{"label":"VW","color":"skyblue"}]"

PHP json_encode JSON_PRETTY_PRINT: how to print a different format?

I know that PHP provide the JSON_PRETTY_PRINT to format a json data already. What if I want a different format?
$message = array(
"Open all day" => "Sundays,Saturdays,12-12-2013, 14-10-2013",
"Availabilty" => array(
"12/12/2013" => array(
30,
60,
30,
0
),
"13/12/2013" => array(
30,
0,
30,
60,
),
),
);
$json = json_encode($message,JSON_PRETTY_PRINT);
result,
{
"Open all day": "Sundays,Saturdays,12-12-2013, 14-10-2013",
"Availabilty": {
"12\/12\/2013": [
30,
60,
30,
0
],
"13\/12\/2013": [
30,
0,
30,
60
]
}
}
But I prefer,
{"Open all day":"
Sundays,
Saturdays,
Fridays,
12/12/2013,
14/10/2013,
04/12/2013
",
"Availability":"
"12/12/2013":[30,60,30,0],
"13/12/2013":[30,60,30,0]
"}
Is that possible? A regex perhaps? Also, I don't want those backslashes - can they be removed?
It isn't possible to get that format using json_encode alone.
But to prevent the slashes from being escaped, you could use the JSON_UNESCAPED_SLASHES constant:
$json = json_encode($message,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
See the documentation here.
Demo!
The php has some constants to ensure that the json is valid, so it is recommended to always use these constants to ensure the integrity of information
http://www.php.net/manual/en/json.constants.php
If you want to use without the escape backslashes you can, provided that the json is formatted nicely, but there is no guarantee that, at some point, or some system refuses your json ... So always use the constants that php provides to ensure the integrity of information.

Categories