Sometimes we receive input data of varying structure, for example response from online API may include some information but other not, some details are stored in complex nested arrays etc.
I like to parse this data before usage, this way I don't have to use isset() over and over later on, ex.:
$input; // source
$correct_data = arra(); // verified data
$correct_data["option-1"] = (isset($input["option-1"]) ? $input["option-1"] : "");
$correct_data["option-2"] = (isset($input["option-2"]) ? $input["option-2"] : "");
Now I can use:
my_function($correct_data["option-1"]);
my_function2($correct_data["option-2"]);
and I know that there won't be any warnings for uninitialized variables or unknown array keys.
But problem occurs for nested data e.g.
$input = array(
"settings-main" => array(
"option-1" => "val-1",
"option-2" => "val-2",
"sub-settings" => array(
"my-option" => "some val",
"my-option-2" => "some val2",
),
),
"other-settings" => array(
"other" => array(
"option-1" => "a",
"option-2" => "b",
),
),
);
It's difficult to check this on start, later I have to use something like this:
if(isset($input["settings-main"]))
{
if(isset($input["settings-main"]["option-1"]))
$input["settings-main"]["option-1"]; //do something
if(isset($input["settings-main"]["sub-settings"]))
{
if(isset($input["settings-main"]["sub-settings"]["my-option-2"]))
$input["settings-main"]["sub-settings"]["my-option-2"]; //do something
}
}
do you have any suggestions how to handle such situations without using multiple isset() instructions ?
Try this with recursive function call.
function recursive_arr($input){
foreach($input as $val){
if(is_array($val)){
recursive_arr($val);
}else{
echo $val."<br/>";
}
}
}
recursive_arr($input);
Working Example
Related
$header_content = array();
$header_content['pageone'][] = array(
'image' => 'photo-one.png',
'desc' => "One. Some text here.",
);
$header_content['pagetwo'][] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
I do not want to echo the entire array, just certain parts when called... like $header_content['pageone']['image'], except this doesn't work... How do you go about echoing parts of an array?
I have searched but it's all a little confusing right now for me. Thanks.
Define it like -
$header_content['pagetwo'] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
The keys are different pageone, pagetwo. No need of that extra index i think. And then access it - echo $header_dontent['pagetwo']['image'];
For printing array values, you can use :
print_r function
Example : print_r($array)
Specific key data can be accessed through : print_r($array[$key])
OR
var_dump function
Example : var_dump($array)
Specific key data can be accessed through : var_dump($array[$key])
use it like $header_content['pageone'][0]['image']
Since
$header_content['pageone'][] = array();
[] appends an element at the end of an array.
So I am writing something to add on to my website.
I have this value stated above:
$settings[] = array(
"name" => "torblock_redirecturl",
"title" => $lang->redirecturl,
"optionscode" => "text",
"disporder" => 1,
"value" => denied.php,
"gid" => $gid
There will be a setting that where someone can enter another url or page. But I have this later in the php file:
die('$torblock_redirecturl');
I want that to change to the value in the setting once the setting is changed.
Aka once a value is entered in the setting, I want the value to change to whatever was entered right in the die.
Thanks for your answers!
You were assigning multidimensional array.
$settings[] = array( "value" => denied.php);
So to get the value access like $settings[0]['value']; the index 0 changes according to number of arrays stored in the $settings
To get expected
die($settings[0]['value']);
Update :
If assigning as single dimensional array.
$settings = array( "value" => denied.php);
Then access it like die($settings['value']);
Try this:
die($settings[0]['name']);
It would be easier to help if you supplied more context, but your syntax error could imply that you wrap an array variable in quotes without escaping, like so:
die('$settings['name']'); // this will break
If you prefer wrapping variables in quotes, you can do it like so:
die("{$settings[0]['name']}");
You may be aware of this, but in your code you're not just assigning an array to the $settings variable:
// this:
$settings[] = array('name' => 'foo');
// is the same as doing this:
$settings = array();
array_push($settings, array('name' => 'foo'));
Could please anyone provide some help in finding a way to process user input (from a post), which is held as variables (obviously) and in which variables' names are correspondent with extracted from database array's keys.
I'm asking this question in hope of getting not just a solution but the best (most concise) possible example.
At the moment, I could achieve it by using loops with if/else and implode/explode, but I thought that there is, maybe, a chance of doing it in some better way, for example, using built-in PHP functions made for processing arrays with usage of anonymous functions at the same time?
Code and comments:
// User id to be processed (extracted from a post)
$id = '8ccaa11';
// Posted new (updated) settings about the user above (extracted from a post)
$individuals_read_access = false;
$individuals_write_access = false;
$calendar_read_access = false;
$calendar_write_access = true;
$documents_read_access = true
$documents_write_access = false
// Current records extracted from database
Array
(
[individuals_read_access] => 8ccaa11
[individuals_write_access] => 8ccaa11
[calendar_read_access] => 8ccaa11|00cc00aa
[calendar_write_access] => 8ccaa11
[documents_read_access] => 8ccaa11
[documents_write_access] => 8ccaa11
)
// Expected array to be posted back to database
Array
(
[individuals_read_access] =>
[individuals_write_access] =>
[calendar_read_access] => 00cc00aa
[calendar_write_access] => 8ccaa11
[documents_read_access] => 8ccaa11
[documents_write_access] =>
)
Could anyone please help to find the best and most concise solution to get expected array?
The problem about an solution using anonymous function is that you cannot access your variables. I created two solutions to demonstrate the case:
Version 1 was removed by request of Illis, see post history :)
Version 2. Inputs as array, use can pass them easily to the anonymous function. Read more about closures and array_walk.
<?php
$id = '8ccaa11';
$inputs = [
'individuals_read_access' => false,
'individuals_write_access' => false,
'calendar_read_access' => false,
'calendar_write_access' => true,
'documents_read_access' => true,
'documents_write_access' => false
];
// Current records extracted from database
$records = [
'individuals_read_access' => '8ccaa11',
'individuals_write_access' => '8ccaa11',
'calendar_read_access' => '8ccaa11|00cc00aa',
'calendar_write_access' => '8ccaa11',
'documents_read_access' => '8ccaa11',
'documents_write_access' => '8ccaa11'
];
array_walk($records, function(&$value, $key) use ($inputs, $id) {
if (!isset($inputs[$key])) {
continue;
}
$rights = empty($value) ? [] : explode('|', $value);
$index = array_search($id, $rights);
if (!$inputs[$key] && $index !== false) {
unset($rights[$index]);
} else {
array_push($rights, $id);
}
$value = implode('|', array_unique($rights));
});
var_dump($records);
i want use json + php for my data. I read more document to do this, and the basic function are json_decode() and json_encode(). My problem is that, read more document and read different example of structure have created in me a lot of doubts.
I want create a structure like this begine from the basic to the container:
there is a Base, that have 2 property: id and value
there is a Operations that can have multiple Base
there is a Command that can have multiple Operations (and if possible a property callad name)
the structure in my mind is like this...
[ //The start of Commands
//Can make a property name here like "name":"puls1"
[ //Operation1
{ //Base1
"id":"22398",
"value":"255"
},
{ //Base2
"id":"22657",
"value":"80",
},
{ //Base3
"id":"7928",
"valore":"15"
}
],
[ //Operation2
{ //Base1
"id":"22398",
"value":"0"
},
{ //Base2
"id":"22657",
"value":"0",
},
{ //Base3
"id":"7928",
"valore":"0"
}
],
] //The close of Commands
But i have put the [ and { in the not correct order i think...
How can i make a json structure like this? And after set a command to insert a new Operation or remove Operation?
Thank's at all..
//Ok by answer of i made this code
class Base
{
var $i;
var $value;
function __construct($i,$v)
{
$this->id = $i;
$this->value = $v;
}
}
$a = new Base('1','11');
$b = new Base('2','10');
$c = new Base ('3','20');
$d = new Base ('4','30');
class Operation
{
var $name;
var $values = Array();
function __construct($a)
{
$this->name = $a;
}
public function addArray($a)
{
array_push($this->values,$a);
}
}
$oper1 = new Operation("op1");
$oper1->addArray($a);
$oper1->addArray($b);
$oper2= new Operation("op2");
$oper2->addArray($c);
$oper2->addArray($d);
$commands = Array($oper1,$oper2);
echo json_encode($tot);
Now the problem is how can i make the revert operation? Such a use of json_decode and incapsulate in its appropriate structure?
The json list type [] is equal to a array without keys in php.
The json dictionary type {}is equal to a keyed array in php.
What you want is something like this:
$json = array(
array(
array('id' => $num, 'value' => $val), // Base 1
array('id' => $num_1, 'value' => $val_1), // Base 3
array('id' => $num_2, 'value' => $val_2), // Base 2
),
array(...),
array(...),
);
If you're working with PHP I would construct the objects from native PHP Classes (json_encode works with php objects as well):
class Base {
var $id;
var $value;
}
Then it's just a matter of putting these objects in various arrays, which you can also abstract with methods like addToOperation($baseObj) and addToCommands($operationObj).
You're dealing with native data structures (Arrays), so you can use native methods to remove (array_pop) and add (array_push) data.
Something like this should work
// Build up your data as a mulitdimensional array
$data = array(
'operations' => array(
0 => array(
'bases' => array (
0 => array(
'id' => '22398',
'value' => 'whatever'
),
1 => array(
'id' => 'id goes here',
'value' => 'value goes here'
),
1 => array(
//data for operation 2
)
);
// Then use json_encode
$json = json_encode($data);
My syntax may not be perfect but that should give you the idea. To access it then you would use code like
$operations = json_decode($data);
foreach ($operations as $op) {
foreach ($op->bases as $base) {
//Logic goes here
}
}
Hope this helps.
I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
So, in JavaScript I can do:
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
But I can't do:
alert(resp.errors.length);
I would like to iterate errors, that's why I'm trying to get the length. Can somebody give me a hint? Thanks!
To be able to do that, you need resp.errors to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using json_encode, the errors PHP array is "translated" to a JS object : your JSON data looks like this :
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
Instead, you would want it to look like this :
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
Notice that "errors" in an array, without named-keys.
To achieve that, your PHP code would need to be :
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
(Just remove the named-keys on errors)
Have a look at your JSON output. resp.errors will be something like this:
{"error1": {"name": "email", "value": "err1"}, ...}
As you can see, it's an object, not an array (since you passed it an associative array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
If you want it to be a JavaScript array, your PHP should look like this:
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
If you inspect the evaluated object in Firebug, you would see that "errors" is not an array but an object(associated arrays in PHP translates to object in JS). So you need to use for-in statement to iterate through an object.
You need to check every property name with hasOwnProperty to be sure that it is something you have sent, not some prototype property.