I am trying to sort the array $result by 'address' below. I have tried usort() but it does not work.
Thanks for all help
foreach ($results as $result) {
$this->data['addresses'][] = array(
'address_id' => $result['address_id'],
'address' => $result['firstname'] . ' ' . $result['lastname'] . ', ' . $result['address_1'] . ', ' . $result['city'] . ', ' . (($result['zone']) ? $result['zone'] . ', ' : FALSE) . (($result['postcode']) ? $r$
'href' => HTTPS_SERVER . 'index.php?route=account/address/' . $type . '&address_id=' . $result['address_id']
);
}
//The following does not work
usort($result, 'address');
To make usort work, you need to define a custom function:
usort($result, function($a, $b){
// ^ anonymous function
return strcmp($a['address'], $b['address']);
});
usort needs a function as second parameter to sort your data, 'address' doesn't seem to be a function
You try to sort $result but you fill $this->data['addresses'] with data
I would fill $this->data['addresses'] with data and use the thing you want to use as key and then use ksort to sort it, example:
foreach ($results as $result) {
$this->data['addresses'][$result['address_id']] = array(
'address_id' => $result['address_id'],
'address' => $result['firstname'] . ' ' . $result['lastname'] . ', ' . $result['address_1'] . ', ' . $result['city'] . ', ' . (($result['zone']) ? $result['zone'] . ', ' : FALSE) . (($result['postcode']) ? $r$
'href' => HTTPS_SERVER . 'index.php?route=account/address/' . $type . '&address_id=' . $result['address_id']
);
}
ksort($this->data['addresses']);
Related
I have this snippet for creating dynamic keyboard:
$keyboard_array = [];
foreach ($verse_arr['items'] as $item) {
$keyboard_array[] = ["text" => '"'. $item['poem']['verse-r'] . '
' . $item['article']['verse-l'] . '
' . $item['article']['poet'] . '
' . $item['article']['book'] . '"' , "callback_data" => '"'.$item['article_id'].'"'];
}
$current = print_r($keyboard_array,true);
$file = 'keyboard.log';
file_put_contents($file, $current);
apiRequestJson("sendMessage", array('chat_id' => $chat_id, "text" => "Search results: ", 'reply_markup' => new InlineKeyboardMarkup(
[
'inline_keyboard' => [$keyboard_array]
])));
As you can see in rows 8-10 I write the results to a file and everything looks fine there. But the message doesn't get through.The text is in UTF-8 and Persian by the way.
I hope you can help me with this.
Regards,
I wrote some code to update a mySQL table via php/PDO.
But it is not working and I just can't figure out where my mistake is.
The execute() returns true, but the changes never actually show up in the table.
My code looks pretty much like this:
$columnObject = array(
"emailAddress"=>"aaa#aaa.com",
"passwordHash"=>"56bj5g63j4g57g567g5k75jh7gk4g74j5hg67",
"name"=>"qweqweqwe",
"lastActivity"=>4128649814
);
$knownColumnName = "emailAddress";
$knownColumnData = "aaa#aaa.com";
foreach ($columnObject as $columnName => $columnData) {
$pdoUpdateString .= $columnName . "=:" . $columnName . ",";
$pdoExecuteObject[$columnName] = $columnData;
}
$pdoUpdateString = rtrim($pdoUpdateString, ",");
$pdoExecuteObject['knownColumn'] = $knownColumnData;
$q = $this->hCon->prepare('UPDATE ' . $this->name . ' SET ' . $pdoUpdateString . ' WHERE ' . $knownColumnName . '=:knownColumn');
$q->execute($pdoExecuteObject);
How can I add variables and quotes to a variable?
in the output it just prints the variables
This is the code I have tried
$pl2 = '{"comment":"' . $nmp3 . '","file":"' . $pmp3 . '"},';
Try with:
$pl2 = json_encode(array(
'comment' => $nmp3,
'file' => $pmp3
));
Try this, it should work:
$p = ' {"comment": ' . $nmp3;
$p = $p.' "," file " : " ' . $pmp3;
$p=$p.' "}," ';
echo $p;
I have the following code:
public function ajax()
{
// Contains results
$data = array();
if( isset($this->request->get['keyword']) ) {
// Parse all keywords to lowercase
$keywords = strtolower( $this->request->get['keyword'] );
// Perform search only if we have some keywords
if( strlen($keywords) >= 3 ) {
$parts = explode( ' ', $keywords );
$add = '';
// Generating search
foreach( $parts as $part ) {
$add .= ' AND (LOWER(pd.name) LIKE "%' . $this->db->escape($part) . '%"';
$add .= ' OR LOWER(p.model) LIKE "%' . $this->db->escape($part) . '%")';
}
$add = substr( $add, 4 );
$sql = 'SELECT pd.product_id, pd.name, p.model FROM ' . DB_PREFIX . 'product_description AS pd ';
$sql .= 'LEFT JOIN ' . DB_PREFIX . 'product AS p ON p.product_id = pd.product_id ';
$sql .= 'LEFT JOIN ' . DB_PREFIX . 'product_to_store AS p2s ON p2s.product_id = pd.product_id ';
$sql .= 'WHERE ' . $add . ' AND p.status = 1 ';
$sql .= ' AND p2s.store_id = ' . (int)$this->config->get('config_store_id');
$sql .= ' ORDER BY LOWER(pd.name) ASC, LOWER(p.model) ASC';
$sql .= ' LIMIT 15';
$res = $this->db->query( $sql );
if( $res ) {
$data = ( isset($res->rows) ) ? $res->rows : $res->row;
// For the seo url stuff
$basehref = 'product/product&keyword=' . $this->request->get['keyword'] . '&product_id=';
foreach( $data as $key => $values ) {
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
}
}
}
}
echo json_encode( $data );
}
So, the array generates a list of products, like for e.g.:
Apple MacBook (Product Model 10)
Apple МакБук (Product Model 10)
The problem is that those two products is actually one and the same product (same product_id) but in different languages, and both have the same URL.
So, what I want to check is, while making the array, the code to check if there is already a product with that product_id in the array, and if there is, not to add another one with the same product_id.
Practically, I don't want the array to generate two or more products with the same product_id.
EDIT: With Marc's code and ghbarratt suggestion work like a charm. A million thanks to you guys, and to all of you here.
P.S. How can I add ASC or DESC for ORDER BY pd.language_id:
$sql .= ' ORDER BY pd.language_id = ' . (int)$this->config->get('config_language_id');
$sql .= ' , LOWER(pd.name) ASC, LOWER(p.model) ASC';
$data = array();
foreach ($res->rows as $values) {
$data[$values['product_id']] = array(
'name' => ...,
'href' => ...
);
}
Guarantees unique product ids only.
The easiest way should be to add another array to track already written ids and check with http://php.net/manual/en/function.in-array.php:
$basehref = 'product/product&keyword=' . $this->request->get['keyword'] . '&product_id=';
$writtenIds = array();
foreach( $data as $key => $values ) {
if(in_array($values['product_id'], $writtenIds))
{
unset($data[$key]);
continue;
}
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
$writtenIds[] = $values['product_id'];
}
This answer is similar to Marc's except it will preserve the other names in an additional element on the data array for the product_id and it will make sure to remove the sub-arrays that have the same product_id as the first encountered one, which I believe is an important part of what you wanted to do.
$product_ids_added = array();
foreach( $data as $key => $values ) {
$original_key = array_search($values['product_id'], $product_ids_added);
if($original_key===false) {
$data[$key] = array(
'name' => htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES),
'href' => $this->url->link($basehref . $values['product_id'])
);
$product_ids_added[] = $values['product_id'];
}
else {
unset($data[$key]);
if(!isset($data[$original_key]['additional_names'])) $data[$original_key]['additional_names'] = array();
$data[$original_key]['additional_names'][] = htmlspecialchars_decode($values['name'] . ' (' . $values['model'] . ')', ENT_QUOTES);
}
}
I'm tying to iterate through an array, assembling a string to return each time.
My question is how can I omit the comma on the last iteration of the array, or if there is only one element to the array? I'm not sure what this operation would be called as my coding skills are very rudimentary, so I've not had much luck searching for an answer. Even help knowing this basic detail would be much appreciated.
this is the result I'd like:
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' },
{ image : 'http://www.site.com/path/to/file/image1.jpg', title : 'Some title and caption' url : 'http://www.site.com/path/to/file/image1.jpg' }
Note the lack of a trailing comma.
Below is the php Im using to generate the strings. It will always include a trailing comma which is causing me all sorts of greif.
//snipit
$i = 1;
$a = '';
foreach ($pages as $go)
{
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$a .= "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
$a .= ",\n";
$i++;
return $a;
}
Many thanks for your experience,
orionrush
$a[] = "{ image :'" . BASEURL . GIMGS . "/$go[media_file]', title : '{$title}, {$caption}', url: '" . BASEURL . GIMGS . "/$go[media_file]' }";
and use it by
return implode(",\n", $a);
You should really use json_encode().
$data = array();
foreach ($pages as $go) {
$title = ($go['media_title'] == '') ? ' ' : $go['media_title'];
$caption = ($go['media_caption'] == '') ? ' ' : $go['media_caption'];
$data[] = array(
'image' => BASEURL . GIMGS . '/' . $go['media_file'],
'title' => $title . ', ' . $caption,
'url' => BASEURL . GIMGS . '/' . $go['media_file']
);
}
echo json_encode($data);
foreach ($pages as $go){
$return[] = json_encode($go);
}
return implode(",\n", $return);
do what you like in the foreach, the implode will comma separate the lines like you want
just chop the end off with substr:
return substr($a, 0, -3);