This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 6 years ago.
I have the following array of arrays:
array(1) {
[0]=>
array(2) {
[0]=>
array(2) {
[0]=>
string(3) "abc"
[1]=>
string(3) "įāē"
}
[1]=>
array(2) {
[0]=>
string(3) "čaē"
[1]=>
string(3) "qwe"
}
}
}
I am using the bellow code to echo the result on a page:
echo json_encode($array);
I get the following result on my page:
[[["abc",null],[null,"qwe"]]]
Every string with special char is converted to null.
So I´ve tried utf8_encode on each of the element in the array:
foreach($array as &$subarray1){
foreach($subarray1 as &$subarray2){
foreach($subarray2 as &$subarray3){
$subarray3 = utf8_encode($subarray3);
}
}
}
But I get the following result:
[[["abc","\u00e1\u00e2\u00e7"],["\u00e8a\u00e7","qwe"]]]
What is the proper way to encode this?
json_encode supports a second parameter so you can use the constant JSON_UNESCAPED_UNICODE like the following:
$arr = [
0 => [0 => "abc", 1 => "įāē"],
1 => [0 => "čaē", 1 => "qwe"]
];
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
You can find a working demo here: https://ideone.com/J5bvT5
Related
So this below is the structure of JSON i have when I decode it in PHP, but for some reason I am having hard time to loop through this JSON object. I don't know how can I get each values of "incident","description","technique" from those array to save them In my DB.
array(1) {
["Access"]=>
array(2) {
[0]=>
array(3) {
["incident"]=>
string(19) "sssssssssssssssssss"
["description"]=>
string(10) "ssssssssss"
["technique"]=>
string(19) "Link "
}
[1]=>
array(3) {
["incident"]=>
string(18) "ssssssssssssssssss"
["description"]=>
string(0) ""
["technique"]=>
string(19) "Link "
}
}
}
So far I have this PHP code but it's returning me an error saying invalid argument in first foreach loop.
$objectFirst =($_POST['Access1']);
$data = json_decode($objectFirst,true);
foreach ($data->Access as $tech){
foreach($tech as $incident){
foreach($incident as $ss){
var_dump($ss->incident);
}
}
}
When you access the element with this notation, $data->Access, it means you try to access a property of the $data object. But in your case, $data is an array, therefore you have to use the array notation.
So it should be corrected as $data['Access']. One other issue in your code is the level of loops.
foreach ($data->Access as $tech){
foreach($tech as $incident){
foreach($incident as $ss){
var_dump($ss->incident);
}
}
}
The inner most loop is incorrect because $incident will contain a string, not an array. When you try to access $ss['incident'], it will fail. So just change it to:
foreach ($data['Access'] as $tech){
foreach($tech as $incident){
var_dump($incident);
}
}
Hope it helps!
<?php
$data = [
'access' =>
[
[
'foo' => 'I',
'bar' => 'got'
],
[
'foo' => 'a',
'bar' => 'big'
]
]
];
foreach($data['access'] as $array)
var_dump($array['foo'], $array['bar']);
Output:
string(1) "I"
string(3) "got"
string(1) "a"
string(3) "big"
Here is my array
$datas = array(array('studentid' => '9','toschool' => '4','tohome'=>'4'),array('studentid' => '10','toschool' => '4','tohome'=>'4'));
When i return this i am getting as
return $data;
Output :
[{"studentid":"9","toschool":"4","tohome":"4"},{"studentid":"10","toschool":"4","tohome":"4"}]
I want to get this same array from the postman
So, i pasted the ouput for the name as data
And i receive it as
$gotdata = Input::get('data');
and when i print i got the same output
[{"studentid":"9","toschool":"4","tohome":"4"},{"studentid":"10","toschool":"4","tohome":"4"}]
When i tried to save the record, the $data works
MYModel::insert($data);
But the
MTIServiceAttendance::insert($gotdata);
And it throws the error as
Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, string given
How can i fix this so that the $gotdata should be saved.
Note : for the Model the input should be
MTIServiceAttendance::insert(array(array('studentid' => '9','toschool' => '4','tohome'=>'4'),array('studentid' => '10','toschool' => '4','tohome'=>'4')));
What should i do to make the input form like this array ?
Update : Here is the var_dump of the arrays
Return :
return var_dump($data);
Output :
array(2) { [0]=> array(3) { ["studentid"]=> string(1) "9" ["toschool"]=> string(1) "4" ["tohome"]=> string(1) "4" } [1]=> array(3) { ["studentid"]=> string(2) "10" ["toschool"]=> string(1) "4" ["tohome"]=> string(1) "4" } }
Return :
return var_dump($gotdata);
Output :
string(94) "[{"studentid":"9","toschool":"4","tohome":"4"},{"studentid":"10","toschool":"4","tohome":"4"}]"
$gotdata is a JSON string representation of your array. So while it looks the same in your first output you can clearly see the difference when using var_dump. Simply use json_decode to convert it in an array:
$gotdata = Input::get('data');
$gotdata = json_decode($gotdata, true);
MTIServiceAttendance::insert($gotdata);
This question already has an answer here:
PHP preg_match to find multiple occurrences
(1 answer)
Closed 8 years ago.
I'm weak with regex, need help. My problem is I have to extract all the string that matches the given pattern I have into an array. See the problem below:
The string
<?php
$alert_types = array(
'warning' => array('', __l("Warning!") ),
'error' => array('alert-error', __l("Error!") ),
'success' => array('alert-success', __l("Success!") ),
'info' => array('alert-info', __l("For your information.") ),
);?>
The Preg_Match Code
preg_match("/.*[_][_][l][\(]['\"](.*)['\"][\)].*/", $content, $matches);
I'm only getting the first one match which is Warning!. I'm Expecting matches will have the following values:
Warning!, Error!, Success!, For your information.
Actually I'm using file_get_contents($file) to get the string.
Can anyone help me to solve this. Thankyou in advance.
preg_match() only finds the first match in the string. Use preg_match_all() to get all matches.
preg_match_all("/.*__l\(['\"](.*?)['\"]\).*/", $content, $matches);
$matches[1] will contain an array of the strings you're looking for.
BTW, you don't need all those single-character brackets. Just put the character into the regexp.
var_dump($matches);
array(2) {
[0]=>
array(4) {
[0]=>
string(45) " 'warning' => array('', __l("Warning!") ),"
[1]=>
string(52) " 'error' => array('alert-error', __l("Error!") ),"
[2]=>
string(58) " 'success' => array('alert-success', __l("Success!") ),"
[3]=>
string(65) " 'info' => array('alert-info', __l("For your information.") ),"
}
[1]=>
array(4) {
[0]=>
string(8) "Warning!"
[1]=>
string(6) "Error!"
[2]=>
string(8) "Success!"
[3]=>
string(21) "For your information."
}
}
I'm trying to parse an array that looks like this:
array(1) {
["StrategischeDoelstellingenPerDepartement"] => array(412) {
[0] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
["Nummer"] => string(2) "27"
["Titel"] => string(22) "DSD 01 - HULPVERLENING"
["IdBudgetronde"] => string(1) "2"
}
[1] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "28"
["Titel"] => string(24) "DSD 02 - Dienstverlening"
["IdBudgetronde"] => string(1) "2"
}
[2] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "29"
["Titel"] => string(16) "DSD 03 - KLANTEN"
["IdBudgetronde"] => string(1) "2"
}
...
(The array goes on but it's too big to post it here in its entirety)
I can do a foreach loop on the array like this:
foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
echo "i found one <br>";
}
However, I want to do the same thing on other arrays and I want to make the function generic. The first key (StrategischeDoelstellingenPerDepartement in this case) can sometimes change, which is why I'd like to do it generically. I've already tried the following:
foreach($my_arr[0] as $row){
echo "i found one <br>";
}
But then I get the following notice, and no data:
Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29
This is probably a silly question, but I'm new to PHP and this seemed like the right way to do it. Obviously, it isn't. Can anyone help me out, please?
Use reset to grab the first element of $my_arr without knowing the key name:
$a = reset($my_arr);
foreach($a as $row){
echo "i found one <br>";
}
Shift the sub-array off the main array and loop over it:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<br>";
}
You are trying to do is object, not array $my_arr->StrategischeDoelstellingenPerDepartement.
You could use isset() to check the index existence:
if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
echo "i found one <br>";
}
}
Or, you could use array_values() to ignore the array keys and to make it an index array:
$my_new_arr = array_values($my_arr);
foreach($my_new_arr as $row){
echo "i found one <br>";
}
Use current ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}
I am trying to json_encode an array which is returned from a Zend_DB query.
var_dump gives: (Manually adding 0 member does not change the picture.)
array(3) {
[1]=>
array(3) {
["comment_id"]=>
string(1) "1"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[2]=>
array(3) {
["comment_id"]=>
string(1) "2"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "test 1"
}
[3]=>
array(3) {
["comment_id"]=>
string(1) "3"
["erasable"]=>
string(1) "1"
["comment"]=>
string(6) "jhghjg"
}
}
The encoded string looks like:
{"1":{"comment_id":"1","erasable":"1","comment":"test 1"},
"2":{"comment_id":"2","erasable":"1","comment":"test 1"},
"3":{"comment_id":"3","erasable":"1","comment":"jhghjg"}}
What I need is:
[{"comment_id":"1","erasable":"1","comment":"test 1"},
{"comment_id":"2","erasable":"1","comment":"test 1"},
{"comment_id":"3","erasable":"1","comment":"jhghjg"}]
Which is what the php.ini/json_encode documentation says it should look like.
How are you setting up your initial array?
If you set it up like:
array(
"1" => array(...),
"2" => array(...),
);
then you don't have an array with numeric indexes but strings, and that's converted to an object in JS world. This can happen also if you don't set a strict order (i.e. starting at 0 instead of 1).
This is a shot in the dark, however, because I can't see your original code: try setting your array without using keys at all in the first place:
array(
array(...),
array(...),
);
Added information that expands on Seb's answer.
php > print json_encode( array( 'a', 'b', 'c' ) ) ;
["a","b","c"]
php > print json_encode( array( 0 => 'a', 1 => 'b', 2 => 'c' ) ) ;
["a","b","c"]
php > print json_encode( array( 1 => 'a', 2 => 'b', 3 => 'c' ) ) ;
{"1":"a","2":"b","3":"c"}
php >
Note: its formatting it this way with good cause:
If you were to send
{"1":"a","2":"b","3":"c"}
as
["a","b","c"]
When you did $data[1] in Php you would get back "a", but on the JavaScript side, you would get back "b" .
A common way to test for a traditional, continuous array in php is to check for an index '0'. Try adding that to your array, it'll probably considering it an array instead of hashmap.
i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string.
Following from my js file:
var myJsVar = <?php echo json_encode($var); ?> ; -------> NOT WORKING
var myJsVar = '<?php echo json_encode($var); ?>' ; -------> WORKING