Passing data in yii dependent dropdown - php

Am creating a depenednt dropdown in yii1 but i always get an error of htmlspecialchars() expects parameter 1 to be string, object given
This is the controller action code
public function actionDistrictList() {
$id = (int)$_POST['province'];
$data = Tblsudistricts::model()->findAll('province_id=1');
Yii::app()->session['districtlist'] = $data; //save created list to session
echo CHtml::tag('option', array('value' => ''), CHtml::encode('[select one]'), true);
foreach ($data as $value => $name){
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
//echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
}}
What could be wrong

Here, In your code
foreach ($data as $value => $name){
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
$value is a index and $name is a object, you have to use its parameters
For eg:
Chtml::encode($name->district_name)
Instaed of:
CHtml::encode($name)

Abhishek's answer is correct. However, you also have an issue with value. $value is the index of the object in the $data array not the id.
It looks like you are expecting a value => name kind of array for $data. If this is the case you should pass $data through the CHtml::listData function.
You can also avoid the foreach loop by using CHtml::listOptions
$data = Tblsudistricts::model()->findAll('province_id=1');
$data = CHtml::listData($data, "id", "name");
Yii::app()->session['districtlist'] = $data;
echo CHtml::listOptions(null, $data, array('prompt' => '[select one]'));

Related

Problem when displaying array session data [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
I have a problem showing the field of the array 'notes' since it does not print the numbers generated by the 'addNotes' function.
The code loads the preloaded data and assigns random numbers with the 'addNotes' function to the 'notes' fields of the array and finally shows the data of the array in showStudentsList ().
<?php session_start();?>
<html>
<body>
<?php
if(!existDataInSession()){
initializePreloadedData();
}
function existDataInSession(){
return $_SESSION['data'] != NULL;
}
function initializePreloadedData(){
$person1= [
'name' => 'person1',
'notes' => []
];
$person2= [
'name' => 'person2',
'notes' => []
];
$data=[$person1,$person2];
$_SESSION['data'] = $data;
}
function addNotes(){
foreach ($data as $key => $value) {
$data[$key]['notes'] = random_int(0,100);
}
}
addNotes();
showStudentsList();
function showStudentsList(){
$data = $_SESSION['data'];
foreach ( $data as $student ) {
echo $student['name'] . " ";
echo $student['notes'];
echo implode($student['notes']);
echo "<br>";
}
}
//Result
//person1 Array
//person2 Array
?>
</body>
</html>
There are several problems in your code.
You change between array and integer notes. The plural implies an array.
You write to a copy of $_SESSION
$_SESSION['data'] != null throws a notice when not defined
Fixed version using notes array:
if(!existDataInSession()){
initializePreloadedData();
}
addNotes();
showStudentsList();
function existDataInSession(){
// we check if data was set. just to make double sure we check for type array as well
return isset($_SESSION['data']) && is_array($_SESSION['data']);
}
function initializePreloadedData(){
$person1= [
'name' => 'person1',
'notes' => []
];
$person2= [
'name' => 'person2',
'notes' => []
];
$_SESSION['data'] = [ $person1, $person2 ];
}
function addNotes(){
// operate on $_SESSION referencing the value since we want to ALTER the session data
foreach ($_SESSION['data'] as &$value) {
// since notes was defined as an ARRAY, we append here
$value['notes'][] = random_int(0,100);
}
}
function showStudentsList(){
$data = $_SESSION['data'];
foreach ( $data as $student ) {
echo $student['name'] . " ";
echo implode(', ', $student['notes']);
echo "<br>", PHP_EOL;
}
}
If I am not wrong to understand your requirement, $data is not defined in addNotes() function:
function addNotes(){
$data = $_SESSION['data']; // fetch data from session
foreach ($data as $key => $value) {
$data[$key]['notes'] = random_int(0,100);
}
$_SESSION['data'] = $data; // assign into session again
}
now use just echo without implode to get notes like echo $student['notes']
Hope this help.

How to get JSON response in to PHP variables

I am getting following response in JSON format and I want it to convert it into PHP variables.
JSON:
{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900"
,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}
output should be PHP:
$transkey = aa900d54-7bfb-47e9-a5de-e423ec34a900;
$vkey = fbb28b32-f439-4801-a434-99c70aa388ca
please advice me how to do it.
Just simply use json_decode();
$result= json_decode($jSon);
var_dump($result); // to see the output
json to array(json_decode) and then extract from array.
$arr = json_decode($json, true);
extract($arr);
var_dump($CreateTransactionResponse);
Output:
array (size=1)
'CreateTransactionResult' =>
array (size=3)
'TransportKey' => string 'aa900d54-7bfb-47e9-a5de-e423ec34a900' (length=36)
'ValidationKey' => string 'fbb28b32-f439-4801-a434-99c70aa388ca' (length=36)
'Messages' =>
array (size=0)
empty
More about extract
use $CreateTransactionResult['TransportKey'] to access Transport Key from JSON. Similarly $CreateTransactionResult['ValidationKey'] for Validation Key.
If you want to access your json try to decode it first:
$result = json_decode($yourJSON, true);
foreach($result['CreateTransactionResponse'] as $key => $val){
echo $transkey = 'TransportKey= ' . $val['TransportKey'] . '<br/>;
echo $vkey = 'ValidationKey= ' . $val['ValidationKey'];
}
Or if it is an array of JSON's
$result = json_decode($yourJSON, true);
$data = [];
foreach($result['CreateTransactionResponse'] as $key => $val){
$data[] = [
'TransportKey' => $val['TransportKey'],
'ValidationKey' => $val['ValidationKey']
];
}
print_r($data);
try this code it will work
$JSON='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900" ,"ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
$arr=json_decode($JSON, TRUE);
foreach ($arr as $value) {
foreach ($arr['CreateTransactionResponse'] as $key => $var) {
echo 'TransportKey = '.$var['TransportKey'].'<br>';
echo 'ValidationKey = '.$var['ValidationKey'].'<br>';
foreach ($var['Messages'] as $key => $msg) {
echo 'Messages = '.$msg.'<br>';
}
}
}
In this case,If its a single and TransportKey and a single ValidationKey value (not an array/object is passed) at a time, this is the simplest. Else if object contains objects or inside objects that we want to use or convert to variable, should use a foreach to loop through the object.
//Debuggig
//The string you provided is converted to a json object
//In your case if it is a json object already pass directly it to $j
//below is just for debugging and understanding
//$json='{"CreateTransactionResponse":{"CreateTransactionResult":{"TransportKey":"aa900d54-7bfb-47e9-a5de-e423ec34a900","ValidationKey":"fbb28b32-f439-4801-a434-99c70aa388ca","Messages":{}}}}';
//$j=json_decode($json);
$transkey=$j->CreateTransactionResponse->CreateTransactionResult->TransportKey;
$vkey=$j->CreateTransactionResponse->CreateTransactionResult->ValidationKey;
echo $transkey."</br>";
echo $vkey."<br/>";
/*result as said:
aa900d54-7bfb-47e9-a5de-e423ec34a900
fbb28b32-f439-4801-a434-99c70aa388ca
*/

PHP variable unexpected result

I have the following code:
include_once("../content/includes/connect.php");
include_once("_functions.php");
//TODO: support sending variables
$check = true;
$callback = "error";
foreach ($_GET as $key => $value) {
echo "Key: {$key}<br>";
echo "Value: {$value}<br>";
echo "<pre>";
print_r(checkRules("register", $key, $value));
echo "</pre>";
list($pass, $errormessage) = checkRules("register", $key, $value);
echo "Pass: {$pass}<br>";
echo "Errormessage: {$errormessage}<br><br>";
if (!$pass) {
$check = false;
$callback = "error";
break;
}
}
if ($check) {
$callback = "register_success";
}
echo json_encode(array(
"callback" => $callback
));
SQL::close();
And this gives me the following HTML page:
Key: email
Value: a#a.aa
Array
(
[pass] => 1
[errormessage] =>
)
Pass:
Errormessage:
{"callback":"error"}
Now I do not get why the list($pass, $errormessage) = checkRules("register", $key, $value); does not work, when I clearly see that with print_r() it has the results.
list(...) = array assignment only works when the array is indexed, but checkRules returns an associative array.
You need to write:
$result = checkRules("register", $key, $value);
$pass = $result['pass'];
$errormessage = $result['errormessage'];
or change checkRules to return an indexed array (not my preference -- indexed arrays should only be used for uniform data).
You could also write:
list($pass, $errormessage) = array_values(checkRules("register", $key, $value));
but I think it's generally poor practice to depend on the order of elements in an associative array.
You're returning an array with string keys. You need to return an array with numeric indices instead, as list expects.
checkRules should be returning [1, ""], not array("pass" => 1, "errormessage" => "").
Change line like this:
list($pass, $errormessage) = array_values(checkRules("register", $key, $value));
list can't work with associative arrays :)

Does it exist any function to dynamically create variables from the key value pair of an array?

Let's say I have this array,
$array = array(
'name' => 'hermet',
'emails' => array ('hermet#example.com',
'hermet#example.net');
);
So this way echo $array ['name'] == 'hermet' prints true. I would like to know if there is a function already embedded in PHP that let me do this:
echo $name == 'hermet'; // obviously 'false'
foreach ($array as $key => $value) {
$aux = $key;
$$aux = $value;
}
echo $name == 'hermet'; // now prints 'true'
It seems to work even with a multidimensional array but I don't know if PHP has already any function to do that.
Thank you in advance.
You might be looking for extract
$array = array(
'name' => 'hermet',
'emails' => array ('hermet#example.com',
'hermet#example.net')
);
extract($array);
var_dump($emails);
echo $name;
-- EDIT: If you are concerned about Paul's remark, supply EXTR_SKIP to the second argument of extract, that way it won't overwrite variable in case you've already defined it prior to calling extract.
$name = 'jason';
extract($array, EXTR_SKIP);
echo $name; // still 'jason'

get array key name passed into the function like $array['key']

Is it possible to get the array key name this way?
$array = ("first" => 1);
function f($object)
{
echo(???); //should give first
}
f($array['first']);
It's not possible if you pass only the value into the function like f($object['first']), the key name has no relation to the passed value in that case.
You need to pass the entire array (f($array)) and use:
echo key($object);
I don't really know what you want to get, but I guess this will help you:
$array = array('foo' => 'bar', 'baz' => 'foobar');
foreach ($array as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
This will return
foo = bar
baz = foobar
I would use
$array = ("first" => 1);
function f($object, $key) {
echo($key); // will give first
echo($object[$key]); // will give 1
}
f($array, 'first');

Categories