Reputation: 140
I need to get the numeric weight of a string which will be used later in the code for sorting alphabetically during page render.
I need to get the weight on the instance I'm working with the string. Strings are not available in an array and there are no list of strings available at that point.
I tried to use ASCII code of string, but that does not work properly.
I'm creating forms with Drupal. The form items have a weight element which can be used to sort items.
For each form item, I have a string name I get from an object (which comes from database). From this string I want to get the weight so that when the form is rendered, the form items will show alphabetically.
This is a snippet of the code I use to build the Drupal form item:
<?php
//string $team_name and int $team_id are available at this point.
//from $team_name, I want to determine a numeric weight here and put in $weight.
$form['team_' . $team_id] = array(
'#type' => 'fieldset',
'#title' => $team_name,
'#collapsed' => FALSE,
'#collapsible' => TRUE,
'#weight' => $weight, //<<<<< Numeric weight to be inserted here.
'#prefix' => '<div class="container-inline">',
'#suffix' => '</div>',
);
?>
Upvotes: 0
Views: 1102
Reputation: 140
I came up with this:
<?php
$weight_string = preg_replace("/[^0-9a-zA-Z]/", "", $string);
$weight = 0;
$weight += ord(substr(strtolower($weight_string), 0)) * 1000;
$weight += ord(substr(strtolower($weight_string), 1)) * 10;
$weight += ord(substr(strtolower($weight_string), 2));
?>
Note the first multiplier, that was the key that solved it.
Upvotes: 0
Reputation: 924
Use the DB to store the form and then when it comes time to render it, pull back in ascending/descending order of the string.
Upvotes: 1
Reputation: 5577
You can generate a weight based on a string
value by looping through an x
amount of characters and retrieving the ASCII value of the letter minus 97 (the letter a
needs to start from 0
). The value of each letter needs to be deduced from a starting weight where the first letter has an higher importance than the second one, and so one ...
Here is an example function that could help you:
// $amount: amount of characters to loop for a given text
// $start_weight: the starting weight, the lower the value, the higher the priority
function _get_weight_from_name($text, $amount = 4, $start_weight = -30)
{
$weight = $start_weight;
for ($i = 0; $i < $amount; ++$i) {
$weight += (ord(substr(strtolower($text), $i)) - 97) / (intval(sprintf('1%s', str_repeat(0, $i))));
}
return round($weight, 2);
}
Upvotes: 1