How to pass an associative array from smarty templates to jquery - php

I have assigned two arrays in selection.php to smarty like this
$country = array(
'1' => 'Japan',
'2' => 'Australia',
'3' => 'India'
);
$city = array(
'1' => array(
'10' => 'Tokyo',
'11' => 'Osaka'
),
'2' => array(
'20' => 'Sydney',
'21' => 'Melbourne'
),
'3' => array(
'30' => 'Mumbai',
'31' => 'Delhi'
)
);
$smarty->assign('country_select',$country);
$smarty->assign('city_select',$city);
$smarty->display('selection.tpl');
The code in selection.tpl looks like this.
<div>{html_options id='country_select' options=$country_select}</div>
<div>{html_options id='city_select' options=$city_select}</div>
Now what I want to do is, write a jQuery function that when I select a country in country_select drop-down, the items in the city_select drop-down will be changed in accordance with the country selection. Means, if I select 'Australia' in the country_select drop-down, in the city-select drop-down except 'Sydney' and 'Melbourne' other options will be removed.
Can you please help me how the jQuery code will be. I have been failed to pass the $city_select array to jQuery.

$country = array('1' => 'Japan', '2' => 'Australia', '3' => 'India');
$city = array(
'1' => array('10' => 'Tokyo', '11' => 'Osaka'),
'2' => array('20' => 'Sydney', '21' => 'Melbourne'),
'3' => array('30' => 'Mumbai', '31' => 'Delhi')
);
$data = array('countries' => $country, 'cities' => $city);
echo json_encode($data);
Use json_encode to echo the output to JSON, the result should look like this:
{"countries":{"1":"Japan","2":"Australia","3":"India"},"cities":{"1":{"10":"Tokyo","11":"Osaka"},"2":{"20":"Sydney","21":"Melbourne"},"3":{"30":"Mumbai","31":"Delhi"}}}
Then you should use jQuery ajax to fetch your PHP and using JSON to communicate
$.get("selection.php", function(result) {
//code here
}, "json");
I wrote an example code on Fiddle, the javascript should put into the middle of above jQuery AJAX.
http://jsfiddle.net/sing0920/X3dvG/
Hope this help.
oops, I found out I totally ignore "smarty" here, sorry for that. But still hope this can help you.

You might use ajax request with JSON data serialization as above. On the other hand you may ommit ajax request, and use $.data functiontion, adding the data-<smth> attribute to some specific element or body. the value of this datat element may be something like:
base64_encode(json_encode($data))
and then use $('<elem>').data('<smth>') in your jquery script and decode it with something like http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html and JSON.parse.

Related

Str_replace inside mutlidimensional array

I have a multidimensional array as follows, which is a PHP array of shoe sizes and their conversions...
$size_array = array(
"M"=>array(
'6'=> array('uk'=>'6','eu'=>'39.5','us'=>'7'),
'6H'=> array('uk'=>'6.5','eu'=>'40','us'=>'7.5'),
'7'=> array('uk'=>'7','eu'=>'40.5','us'=>'8'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'8.5'),
'8'=> array('uk'=>'8','eu'=>'42','us'=>'9'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'9.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'10'),
'9H'=> array('uk'=>'9.5','eu'=>'44','us'=>'10.5'),
'10'=> array('uk'=>'10','eu'=>'44.5','us'=>'11'),
'10H'=> array('uk'=>'10.5','eu'=>'45','us'=>'11.5'),
'11'=> array('uk'=>'11','eu'=>'46','us'=>'12'),
'11H'=> array('uk'=>'11.5','eu'=>'46.5','us'=>'12.5'),
'12'=> array('uk'=>'12','eu'=>'47','us'=>'13'),
'12H'=> array('uk'=>'12.5','eu'=>'48','us'=>'13.5'),
'13'=> array('uk'=>'13','eu'=>'48.5','us'=>'14')
),
"F"=>array(
'3'=> array('uk'=>'3','eu'=>'35.5','us'=>'5'),
'3H'=> array('uk'=>'3.5','eu'=>'36','us'=>'5.5'),
'4'=> array('uk'=>'4','eu'=>'37','us'=>'6'),
'4H'=> array('uk'=>'4.5','eu'=>'37.5','us'=>'6.5'),
'5'=> array('uk'=>'5','eu'=>'38','us'=>'7'),
'5H'=> array('uk'=>'5.5','eu'=>'38.5','us'=>'7.5'),
'6'=> array('uk'=>'6','eu'=>'39','us'=>'8'),
'6H'=> array('uk'=>'6.5','eu'=>'39.5','us'=>'8.5'),
'7'=> array('uk'=>'7','eu'=>'40','us'=>'9'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'9.5'),
'8'=> array('uk'=>'8','eu'=>'41.5','us'=>'10'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'10.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'11'),
'9H'=> array('uk'=>'9.5','eu'=>'43.5','us'=>'11.5'),
'10'=> array('uk'=>'10','eu'=>'44','us'=>'12')
)
);
The array is part of a function that returns the conversions based on a supplied size and gender (i.e. SizeConvert('M','6') returns Array ([uk] => 6, [eu] => 39.5,[us] => 7)).
I want to extend the function to allow the passing of a value which will return the array results with any .5 values replaced with ½ (or ½) (i.e. SizeConvert('M','6','Y') returns Array ([uk] => 6, [eu] => 39½,[us] => 7))
How do I make str_replace (or a more appropriate command) iterate over the array and replace the values?
I've tried something like str_replace(".5", "&frac12", $size_array) but I guess that's not working as it's only looking at the initial array, not the sub-arrays.
You are trying to apply this to a multidimensional array without real reason. If you have your SizeConvert function ready and returning a one dimensional array, simply apply the transformation before returning the value:
function SizeConvert(/* other parameters */, bool $convertOneHalf) {
$match = ... // your code to find the match
return $convertOneHalf
? str_replace('.5', '½', $match)
: $match;
}
Based on the boolean value of the parameter that dictates whether the conversion should be applied, we either return the modified or the unmodified result through the ternary.
Do not overthink it and use a for loop to loop through all the elements in the array and use an if...else... to check for 0.5
if($array[index]=="0.5") {
$array[index]="½";
} else {
$array[index]=str_replace(".5", "½", $array[index]);
}
I coded up a simple code, it's not exactly the answer to your question but u can use the logic behind it. The code below will change all the 0.5 in the array to 1⁄2 but since u already acquire the data, there is no need to have so much nested-loop, just 1 level of the loop to loop through all ur elements in your array is enough.
<?php
$size_array = array(
"M" => array(
'6' => array(
'uk' => '6',
'eu' => '39.5',
'us' => '7'
) ,
'6H' => array(
'uk' => '6.5',
'eu' => '40',
'us' => '7.5'
) ,
'7' => array(
'uk' => '7',
'eu' => '40.5',
'us' => '8'
)
) ,
"F" => array(
'3' => array(
'uk' => '3',
'eu' => '35.5',
'us' => '5'
) ,
'3H' => array(
'uk' => '3.5',
'eu' => '36',
'us' => '5.5'
) ,
'4' => array(
'uk' => '4',
'eu' => '37',
'us' => '6'
)
)
);
foreach ($size_array as $firstLevel)
{
foreach ($firstLevel as $secondLevel)
{
foreach ($secondLevelas $values)
{
if ($values== "0.5")
{
echo $values= "½";
}
else
{
echo $values= str_replace(".5", "½", $values);
}
}
}
}
?>

Parsing information from PHP Object

I need some help trying to parse informaiton ti display in a form. Right now when using the basic array an address is returned as "3 Columbus PlaceApt1" where Address 1 and Address 2 are returned joined together. I created an object that returns this with print_r
a:2:{
s:18:"_gravity_form_lead";a:16:{
s:4:"19.1";s:28:"Stamford PD Extra Duty Order";s:4:"19.2";s:5:"$0.00";s:4:"19.3";s:0:"";s:3:"9.1";s:16:"3 Columbus Place";s:3:"9.2";s:5:"Apt 1";s:3:"9.3";s:0:"";s:3:"9.4";s:11:"Connecticut";s:3:"9.5";s:0:"";s:3:"9.6";s:13:"United States";i:22;s:14:"(203) 123-4567";i:12;s:10:"2016-05-24";i:13;s:8:"12:35 am";i:20;s:8:"8|584.64";i:11;s:9:"MH6151684";i:21;s:1:"3";i:18;s:7:"1753.92";}s:18:"_gravity_form_data";a:15:{s:2:"id";s:1:"6";s:13:"display_title";b:0;s:19:"display_description";b:0;s:25:"disable_woocommerce_price";s:3:"yes";s:12:"price_before";s:0:"";s:11:"price_after";s:0:"";s:20:"disable_calculations";s:2:"no";s:22:"disable_label_subtotal";s:3:"yes";s:21:"disable_label_options";s:3:"yes";s:19:"disable_label_total";s:2:"no";s:14:"disable_anchor";s:2:"no";s:14:"label_subtotal";s:8:"Subtotal";s:13:"label_options";s:7:"Options";s:11:"label_total";s:5:"Total";s:8:"use_ajax";s:2:"no";
}
}
I want to parse our s:16 and s:5 but im not sure how to do it. Any help is appreciated
EDIT
Unserialized string:
array ( '_gravity_form_lead' => array ( '19.1' => 'Stamford PD Extra Duty Order', '19.2' => '$0.00', '19.3' => '', '9.1' => '3 Columbus Place', '9.2' => 'Apt 1', '9.3' => '', '9.4' => 'Connecticut', '9.5' => '', '9.6' => 'United States', 22 => '(203) 123-4567', 12 => '2016-05-24', 13 => '12:35 am', 20 => '8|584.64', 11 => 'MH6151684', 21 => '3', 18 => '1753.92', ), '_gravity_form_data' => array ( 'id' => '6', 'display_title' => false, 'display_description' => false, 'disable_woocommerce_price' => 'yes', 'price_before' => '', 'price_after' => '', 'disable_calculations' => 'no', 'disable_label_subtotal' => 'yes', 'disable_label_options' => 'yes', 'disable_label_total' => 'no', 'disable_anchor' => 'no', 'label_subtotal' => 'Subtotal', 'label_options' => 'Options', 'label_total' => 'Total', 'use_ajax' => 'no', ), )
You're doing this the hard way!
This is WordPress. You don't need to get a record, unserialize it, try and guess at the structure, etc.
Instead, use the get_option or get_postmeta functions to get the information you want.
Further, there's documentation for both WooCommerce and Gravity Forms that will explain how to get the information you're looking for - BUT, this is a bit of an XY Problem - you've asked how to parse an array (Serialized) - but REALLY you are trying to do something else. You should ask THAT question, rather than the details of this question.
If you must do this manually, do not use unserialize. Instead, use the WordPress function maybe_unserialize
Lastly, the way Gravity Forms stores records is a major nuisance. It's very difficult to map the way it is stored to the "form field" that you set up in the form - unless you use the Gravity Forms API, which makes it somewhat better.
You have to unserialize the array to get the data you need. Like this:
$formData = unserialize($var);
// This is Address1
echo $formData['_gravity_form_lead']['9.1'];
echo "<br/>";
// This is Address2
echo $formData['_gravity_form_lead']['9.2'];

CakePHP: Load name field of related model on view

Guys I have a simple but boring question...
I have the following scenario:
Solicitation -> HasMany -> Destiny
Destiny -> BelongsTo -> City
My problem is on the view, I want to retrieve the City name instead of the city_id and I can't figure out.
Here is my Result:
array (size=12)
'Solicitation' =>
array (size=32)
'id' => string '25' (length=2)
'Destiny' =>
array (size=2)
0 =>
array (size=3)
'id' => string '3' (length=1)
'solicitation_id' => string '25' (length=2)
'city_id' => string '4382' (length=4)
1 =>
array (size=3)
'id' => string '4' (length=1)
'solicitation_id' => string '25' (length=2)
'city_id' => string '4350' (length=4)
How can I retrieve the city name on the view?
Here's my controller:
public function mySolicitations()
{
$this->Solicitation->recursive = 1;
$person_id = $this->Auth->user('id');
$conditions = array(
'Solicitation.created_by' => $person_id
);
$this->set(array(
'data' => $this->paginate('Solicitation', $conditions, array('Solicitation.id' => 'DESC')),
'title_for_layout' => 'My Solicitations'
));
}
Is there a problem with my relation?
Thanks in advance.
There are two ways:
Change your model recursive value to 2.
$this->Solicitation->recursive = 2;
The drawback of using this is when you have quite a few associations involved, it'll retrieve a lot of unwanted unnecessary data.
You can use "Containable" Behavior here.
$this->Solicitation->Behaviors->load("Containable");
And specify the model names that you want to retrieve:
$this->Solicitation->contain(array(
"Destiny", "Destiny.City"
)
);
Then add your code:
$conditions = array(
'Solicitation.created_by' => $person_id
);
$this->set(array(
'data' => $this->paginate('Solicitation', $conditions, array('Solicitation.id' => 'DESC')),
'title_for_layout' => 'My Solicitations'
));
If you debug, you'll certainly find the "City" index within each Destiny sub arrays.
Hope this helps.
Peace! xD

How to turn sql result to multi-dimensional array dynamically?

Here is the query string.
$query = "SELECT t.id, t.assignee, t.owner,
d.code, d.status, d.target_completion_date,
d.target_extension_date, d.submission_date, d.approval_date,
d.revision_start_date, d.revision_completion_date, d.message,
ty.name, f.orig_name, f.new_name,
b.payment_date, b.discount, b.total_cost, b.amount_payed, b.edit_level,
b.billing_type, b.pages, b.words
FROM tasks t
INNER JOIN details d ON t.detail_id = d.id
INNER JOIN billing b ON t.billing_id = b.id
INNER JOIN TYPE ty ON d.document_type_id = ty.id
INNER JOIN files f ON t.file_id = f.id
WHERE t.assignee = 'argie1234'";
And this is the array i would like the query result to turn into.
$user = array('allTask'=>array(array('taskid' => 1,
'assignee'=>'argie1234',
'owner'=>'austral1000',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' =>'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
array('taskid' => 12,
'assignee'=>'argie1234',
'owner'=>'usaroberto',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' => 'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
'account' => array( 'username' => 'marooon55',
'emailadd' => 'marooon#yahoo.com',
'firstname' => 'Maroon',
'initial' => 'E',
'lastname' => 'Young',
'country' => 'Australia',
'gender' => 'M',
'password' =>'360e2801190744a2af74ef6cbfdb963078b59709',
'activationDate' => '2013-09-13 14:30:34') );
How can i create the above array? I sure know how to define multi dimensional array, regretfully though i am having difficulty creating this complex array dynamically. As a beginner i don't even know where to begin.
Here is an example that might help you out. Try starting with simple multi dimensional arrays, once you get a hold of it, you can move onto building complex ones. You will then find that the array you want to build is not really difficult than you initially thought it to be.
$mycomplexarray = array('key1' => array('val1', 'val2'),
'key2' => array('val3', 'val4' => array('val5', 'val6')
)
);
You could create the array just as you have here. I'm not gonna write the whole thing out, but something like this...
$result = $mysqli->query($query); // however you query the db is up to you.
$row = $result->fetch_assoc(); //same as query use your prefered method to fetch
$user = array('allTask'=>array(array('taskid' => $row['id'],
'assignee'=>$row['assignee'],
'owner'=>$row['owner'],
'details' => array( 'code' => $row['code'],
'status'=>$row['status'],
...etc, Hope this makes sense for you.
Set up a structure array first that defines which columns will be stored in a sub array like
$struc=array('Id'->0, 'assignee'->0, 'owner'->0,
'code'->'detail', 'status'->'detail', 'target_completion_date'->'detail',
'target_extension_date'->'detail', 'submission_date'->'detail', 'approval_date'->'detail',
'revision_start_date'->'detail', 'revision_completion_date'->'detail', 'message'->'detail',
'name'->'file', 'orig_name'->'file', 'new_name'->'file',
'payment_date'->'billing', 'discount'->'billing', 'total_cost'->'billing', 'amount_payed'->'billing', 'edit_level'->'billing', 'billing_type'->'billing', 'words');
In your while ($a=mysqli_fetch_assoc($res)) loop you can now use this structure to decide whether you want to store an element directly in your target array or whether you want to place it in the subarray named in this structure array. Like
$res=mysqli_query($con,$sql);
$arr=array();
while($a=mysqli_fetch_assoc($res)) {
// within result loop: $a is result from mysqli_fetch_assoc()
$ta=array(); // temp array ...
foreach ($a as $k => $v){
if ($struc[$k]) $ta[struc[$k]][$k]=$v;
else $ta[$k]=$v;
}
$arr[]=$ta; // add to target array
}
This is the complete code, no more is needed. It was typed up on my iPod, so it is NOT tested yet.
The generated array should be equivalent to your $user['allTask'] array.

jQuery order json list from php?

i am sending an ordered json_encode list of some MySQL tables, from php, but when i retrieve it with jquery it is not in order any more? everything works fine and in order on the php side. it's the client side that i'm having trouble with. i think the problem is that i'm sending a multidimensional array from php as json. what would be the most efficient solution? also why has the order changed when retrieved by jQuery.
PHP CODE:
$user_data = array();
while($row = mysql_fetch_array($retval, MYSQL_ASSOC){
$user_id = $row['user_id'];
if(!isset($user_data[$user_id]){
$user_data[$user_id] = array(
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'dept' => $row['dept'],
'quals' => array()
);
}
$quals = array(
'qual_cat' => $row['qual_cat'],
'qual' => $row['qual'],
'count' => $row['count']
)
$user_data[$user_id]['quals'][] = $quals;
}
echo json_encode($user_data);
jQuery:
$.post('page.php', function(post){
$.each(post, function(i,data){
alert(data.first_name+' '+data.last_name+' - '+data.dept);
});
});
PHP VAR_DUMP:
array
10 =>
array
'first_name' => string 'David' (length=5)
'last_name' => string 'Dan' (length=3)
'dept' => string 'web' (length=3)
'count' => string '5' (length=1)
'quals' =>
array
0 =>
array
...
1 =>
array
...
2 =>
array
...
3 =>
array
...
4 =>
array
...
In php, array is by default associative, so that's why you have this behavior as associative array order is not guaranteed (as per explanation in the link given by benedict_w).
To overcome this, you could try the following:
echo json_encode(array_values($user_data));
This will effectively turn your json from
["10":{prop1:val1, prop2:val2}, "25":{prop1:val1, prop2:val2}]
into
[{prop1:val1, prop2:val2}, {prop1:val1, prop2:val2}]
If you need to keep track of the id, put it inside your user_data in your php:
if(!isset($user_data[$user_id]){
$user_data[$user_id] = array(
'id' => $user_id,
'first_name' => $row['first_name'],
'last_name' => $row['last_name'],
'dept' => $row['dept'],
'quals' => array()
);
}

Categories