Suppose I have a JSON string:
$json = '{"lemon":"test",
"orange":["toto", "tata", "tete"],
"zob":[{"id":"0"}, {"id":"1"}]}';
I'd like to cycle through that encoded object to modify every string in it, so I have a recursive function:
function doObject($__obj){
$__obj = cycleObject($__obj);
return $__obj;
}
function cycleObject($__obj){
$type = gettype($__obj);
foreach($__obj as $var => &$val){
switch(gettype($val)){
case 'object':
cycleObject($val);
break;
case 'array':
cycleObject($val);
break;
case 'string':
if($type == 'object'){
$__obj->$var = $val.'-ok';
}else{
if($type == 'array'){
$__obj[$var] = $val.'-ok';
}
}
break;
}
}
return $__obj;
}
And I call the function:
$obj = doObject(json_decode($json));
var_dump($obj);
Which gives :
object(stdClass)#1 (3) {
["lemon"]=> string(7) "test-ok"
["orange"]=> array(3) {
[0]=> string(4) "toto"
[1]=> string(4) "tata"
[2]=> string(4) "tete" }
["zob"]=> array(2) {
[0]=> object(stdClass)#2 (1) {
["id"]=> string(4) "0-ok" }
[1]=> object(stdClass)#3 (1) {
["id"]=> string(4) "1-ok" }
}
}
Now my problem is, for some reason, I am unable to modify directly inside an array composed by string, or should I say, the modified string inside an array (and not inside an object inside an array) because the array loses its reference. How do I fix that so in orange I instead obtain:
[0]=> string(7) "toto-ok"
[1]=> string(7) "tata-ok"
[2]=> string(7) "tete-ok"
Your array of strings isn't being scrutinized correctly by your function. Basically, in each array you need a second check to see if you are dealing with another array/object or a string, otherwise regular arrays of strings are being bypassed....oddly enough. The following should work for you:
$json = '{"lemon":"test",
"orange":["toto", "tata", "tete"],
"zob":[{"id":"0"}, {"id":"1"}]}';
function doObject($__obj){
$__obj = cycleObject($__obj);
return $__obj;
}
function cycleObject($__obj){
foreach($__obj as $key => &$val){
if(is_object($val)) {
cycleObject($val);
}
if(is_array($val)) {
foreach($val as &$v) {
if(is_object($v) || is_array($v)) {
cycleObject($v);
} else {
$v .= '-ok';
}
}
}
if(is_string($val)) {
$val .= '-ok';
}
}
return $__obj;
}
$obj = doObject(json_decode($json));
var_dump($obj);
This produced the results you were looking for in my local environment.
object(stdClass)#1 (3) {
["lemon"]=>
string(7) "test-ok"
["orange"]=>
array(3) {
[0]=>
string(7) "toto-ok"
[1]=>
string(7) "tata-ok"
[2]=>
string(7) "tete-ok"
}
["zob"]=>
array(2) {
[0]=>
object(stdClass)#2 (1) {
["id"]=>
string(4) "0-ok"
}
[1]=>
object(stdClass)#3 (1) {
["id"]=>
string(4) "1-ok"
}
}
}
Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>
I'm receiving a JSON and trying to interpret some values using PHP.
Example snippet from a JSON dump:
["11811"]=>
object(stdClass)#15 (11) {
["parent_area"]=>
NULL
["generation_high"]=>
int(19)
["all_names"]=>
object(stdClass)#16 (0) {
}
["id"]=>
int(11811)
["codes"]=>
object(stdClass)#17 (3) {
["ons"]=>
string(2) "08"
["gss"]=>
string(9) "E15000008"
["unit_id"]=>
string(5) "41421"
}
["name"]=>
string(10) "South East"
["country"]=>
string(1) "E"
["type_name"]=>
string(15) "European region"
["generation_low"]=>
int(1)
["country_name"]=>
string(7) "England"
["type"]=>
string(3) "EUR"
}
As there is lots of (nested) data, I need to obtain the value of ["name"] where ["type_name"] == 'European region'.
Thanks.
You could use array_filter()
$data_array = array(...);
function is_european($data) {
return $data->type_name == 'European region';
}
$filtered = array_filter($data_array,'is_european');
And then use filtered array to obtain values.
Maybe a better way would be to use JsonPath, like this, assuming your array is a result of decoding JSON (object):
$names = jsonPath($data_object, "$.[?(#['type_name'] == 'European region')].name");
Haven't tried this myself, it may need a bit of correction.
Try this:
<?php
$json = JSON_decode(str,true);
$arr = Array();
foreach($json as $f) {
/* eg. $f = $json["11811"] */
if($f['type_name'] == 'European region') {
$arr[] = $f['name'];
}
}
?>
I'm trying to add another column of data to each row in a foreach loop. It's purpose is to remember the element of data importeded from XML processed to an multidimensional array. It's stuck as a scalar though the var_dumps looks fine.
<?php
$KEY = 0;
foreach ($eventsArray as $keyMe){
$thisKey['KEY'][0] = strval($KEY);
$keyedArray = array_merge($keyMe, $thisKey);
$KEY++;
}
// Prep for multisort
foreach ($keyedArray as $key => $value){
$date[$key] = $value['DATE'];
$title[$key] = $value['TITLE'];
$link[$key] = $value['LINK'];
$slide[$key] = $value['SLIDE'];
$location[$key] = $value['LOCATION'];
$time[$key]= $value['TIME'];
$KEY[$key] = $value['KEY']; // Warning: Cannot use a scalar value as an array
}
/* var_dump(
array(7) {
["DATE"]=> array(1) { [0]=> string(10) "2012-12-18" }
["TITLE"]=> array(1) { [0]=> string(20) "Event Title" }
["LINK"]=> array(1) { [0]=> string(38) "aLinkLocation.htm" }
["SLIDE"]=> array(1) { [0]=> string(2) "16" }
["LOCATION"]=> array(1) { [0]=> string(8) "Location of Event" }
["TIME"]=> array(1) { [0]=> string(3) "8am" }
["KEY"]=> array(1) { [0]=> string(2) "23" }
}
*/
array(2) {
["names"]=> array(4) {
[0]=> string(4) "Edit"
[1]=> string(6) "Delete"
[2]=> string(8) "Activate"
[3]=> string(10) "Deactivate"
}
["action"]=> array(4) {
[0]=> string(4) "ajax"
[1]=> string(4) "abc"
[2]=> string(4) "def"
[3]=> string(4) "xyz"
}
}
How do i loop through this in a single foreach loop?
Assuming both arrays are of the same size and have the same keys:
foreach($array['names'] as $k => $name) {
$action = $array['actions'][$k];
// do whatever you want to do with $name and $action
}
$newArr = array();
foreach($data['names'] as $i => $val) {
$newArr[$val] = $data['actions'][$i];
}
Or if you want a one liner at that
$newArr = array_combine($data['names'], $data['action']);
I guess the best way is a recursive function which can move through even three dimensions and more
function MoveThroughArray($arr)
{
foreach($arr as $value)
{
if(is_array($value))
MoveThroughArray($value);
else
// Do Something
}
}