Cannot access element in array converted from stdClass created by json_decode - php

$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";
var_dump($arr);
$arr = json_encode($arr);
$arr = (array)json_decode($arr);
var_dump($arr);
var_dump( $arr[1]);
var_dump( $arr["1"]);
The output of 2 last var_dump are NULL NULL, if we remove the 4th line $arr["other_option"] = "2123"; it'll ouput correctly, but I don't understand why!

instead of type casting to array , set true in json_encode
When TRUE, returned objects will be converted into associative arrays.
$arr = array();
$arr[0] = "2a123";
$arr[1] = "2123";
$arr["other_option"] = "2123";
$arr = json_encode($arr);
$arr = json_decode($arr,true);
var_dump( $arr['other_option']); // return 2123
working DEMO

Related

after json decode merge

after json decode array merge
$permission_roles1 = DB::table('permission_roles')->select('permission_name')->first();
$permission_roles2 = DB::table('user_permissions')->select('userP_name')->first();
$json_array1 = json_decode($permission_roles1->permission_name);
$json_array2 = json_decode($permission_roles2->userP_name);
$arr1 = array($json_array1);
$arr2= array($json_array2);
$res = array_merge($arr1, $arr2);
dd($res);
In your code,
$json_array1 = json_decode($permission_roles1->permission_name);
$json_array2 = json_decode($permission_roles2->userP_name);
returns object not an array.
Just changed it to
$json_array1 = json_decode($permission_roles1->permission_name, true);
$json_array2 = json_decode($permission_roles2->userP_name, true);
convert array object into array then merge the array
$permission_roles1 = DB::table('permission_roles')->select('permission_name')->first();
$permission_roles2 = DB::table('user_permissions')->select('userP_name')->first();
$arr1 = (array) $permission_roles1->permission_name;
$arr2 = (array) $permission_roles2->userP_name;
$res = array_merge($arr1, $arr2);
dd($res);

$array variable isn't equal to $GLOBALS['players'][$name] when defined as $GLOBALS['players'][$name] = array()

Using the code below it doesn't work but when I use
<?php
$GLOBALS['players'] = array();
function add($name) {
$array = $GLOBALS['players'][$name] = array();
array_push($array, "b");
}
add("a");
print_r($players);
?>
(outputs: Array ( [a] => Array ( ) )) the code here
<?php
$GLOBALS['players'] = array();
function add($name) {
$array = $GLOBALS['players'][$name] = array();
array_push($GLOBALS['players'][$name], "b");
}
add("a");
print_r($players);
?>
(outputs: Array ( [a] => Array ( [0] => b ) )) it works fine. Why does $array not work when it is referencing the same array.
It's very simple, when you pass the values to $array you're passing the $GLOBAL array to a new variable, you're not referencing the variable $GLOBAL variable.
In a few words: $array and $GLOBAL are two differents variables. Doing this is like doing:
$a = 10;
$b = $a;
$b++;
print_r($a); // Will not print 11, but 10, because you edited the var $b, that is different from $a.
To solve this little trouble you must pass the variable to $array by referencing it like here:
function add($name) {
$GLOBALS['players'][$name] = array();
$array = &$GLOBALS['players'][$name];
array_push($array, "b");
}

combine strings into an array in php

I have a web service to identify people and their functions from an external database that returns me a set of data if the login is successful. The data (that interests me right now) is separated in different strings as follow:
$groups="group1, group2, group3"
$functions="member, member, admin"
The first element of the string $groups corresponds to the first element of the $functions string.
We can have empty spots in the strings:
$groups="group1,, group3";
$functions="member,, admin";
What is the best way to combine them to obtain:
$usertype(
group1=>member,
group2=>member,
group3=>admin,
);
Then I plan to use array_search() to get the name of the group that corresponds to a function.
This is very trick especially when the first element is empty but here is a comprehensive solution
What you need is :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
If you need to fix null values then :
Example :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
See Live DEMO
More Complex:
// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";
// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group4] => member
[group5] => member
[group6] => member
[group3] => admin
)
Live DEMO
Function Used
function fixNull($array, $inc = false) {
$ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
if ($inc) {
$next = array_filter($array);
$next = current($next);
$next ++;
} else {
$next = array_filter($array);
sort($next);
$next = end($next);
}
$next || $next = null;
$modified = array();
foreach($ci as $item) {
$modified[] = empty($item) ? trim($next) : trim($item);
if (! $ci->getInnerIterator()->current()) {
$item || $item = $next;
$next = $inc ? ++ $item : $item;
}
}
return $modified;
}
$groups = explode(",", $groups);
$functions = explode(",", $functions);
//then use the elements of the $groups array as key and the elements of the $functions array as the value
$merged = array_combine($groups, $functions);
Something along the lines of this should help:
$usertype = array_combine(explode(',', $groups), explode(',', $functions));
Use explode() to make arrays of your strings, and array_combine() to use one array as keys, the other one as values.
$groups = "group1, group2, group3";
$functions = "member, member, admin";
$usertype = array_combine(explode(", ", $groups), explode(", ", $functions));
Have you tried a explode($delimiter , $string) and then filter the array? I think that would be a good way of doing it:
$groups="group1,, group3";
$functions="member,, admin";
$groups_array = array_map('trim',explode(',', $groups));
$functions_array = array_map('trim',explode(',', $functions));
$final = array();
for ($i = 0; $i <= count($groups_array); $i++) {
$final[$groups_array[$i]] = $functions_array[$i];
}
$merged = array_combine($groups_array, $functions_array);
Demo
$groups="group1, group2, group3"
$functions="member, member, admin"
preg_match_all('/\w+/', $groups, $groups);
preg_match_all('/\d+/', $functions, $functions);
$final = array();
foreach ($groups[0] AS $key => $letter)
$final[] = $letter . '=>' . $functions[0][$key];
echo join(', ', $final);
explode and array_combine.
Note that you have a problem with whitespaces. Therefore use the following:
<?php
$groups="group1, group2, group3";
$functions="member, member, admin";
$groupArray = array_map(function($element){return trim($element);},
explode(',',$groups)); // split into array and remove leading and ending whitespaces
$functionArray = array_map(function($element){return trim($element);},
explode(',',$functions)); // split into array and remove leading and ending whitespaces
print_r(array_combine($groupArray,$functionArray));
?>
This will output:
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
EDIT: removed trim for the possibility that the first element is empty.

Add new lines to JSON

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?
json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"
Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);

PHP string to nested array

I need to convert a string from an ldap query. I am querying my Active Directory server for user accounts. This is the string that I pulled.
"CN=Phil Robertson,OU=Users,OU=Duck Commander,OU=Department & Buildings,DC=OCSDtest,DC=local"
I would want it converted to an array that looks like this
$array['local']['OCtest']['Department & Buildings']['Duck Commander']['Users']['Phil Robertson']=1;
NOT
$array( [1]=>'local,[2]=>'OCtest',[3]='Depart',[4]='Duck Commander',[5]='Users');
So far I have
Example code ---
$dnn2 = ldap_explode_dn("CN=Phil Robertson,OU=Users,OU=Duck Commander,OU=Department & Buildings,DC=OCSDtest,DC=local",1);
unset($dnn2['count']);
echo "<pre>";
print_r(array_reverse($dnn2));
What am I needing?
Try this
$arrayvalue = array();
foreach($dnn2 as $dn)
{
$temp = explode('=',$dn);
$temp1 = substr($temp[1], 0, strpos($temp1[1], ','));
$arrayvalue[] = $temp1;
}
print_r($arrayvalue);
$dnn2 = ldap_explode_dn("CN=Phil Robertson,OU=Users,OU=Duck Commander,OU=Department & Buildings,DC=OCSDtest,DC=local",1);
unset($dnn2['count']);
$result = null;
$ref =& $result;
foreach (array_reverse($dnn2) as $dn) {
$ref = array($dn => null);
$ref =& $ref[$dn];
}
print_r($result);
Try this
$a = array();
foreach($dnn2 as $dn)
{
$arr = explode('=',$dn);
$a[] = $arr[1]; //or $a[] = array($arr[1]); for 6 dimensional array
}
print_r($a);

Categories