retrieve database values and then replace values with images outside of database - php

I cannot get my head around how to do this.
I have a mysql table called 'companies' that has a column called 'language'. This language column contains country abbreviations (en, de, es...).
Then I have flags saved in media/images/flags (en.png, de.png, es.png...).
I do not want to save the flags in db but I want to change db-country abbrevs. into flags inside the code. Below, I store the country abbrevs from db inside abbrevs. and try somehow to match them to array keys.
Model (platform_model):
public function get_country(){
$query = $this->db->query("SELECT language FROM companies");
return $query;
}
Controller:
public function set_flag(){
$this->load->model('platform_model');
$abbrevs = $this->platform_model->get_country();
$flags = array(
'de' => base_url('media/images/flags/de.png'),
'en' => base_url('media/images/flags/en.png'),
'it' => base_url('media/images/flags/it.png'),
'fr' => base_url('media/images/flags/fr.png'),
'es' => base_url('media/images/flags/fr.png'),
'pt' => base_url('media/images/flags/pt.png'),
'ru' => base_url('media/images/flags/ru.png'),
'ch' => base_url('media/images/flags/ch.png'),
'ja' => base_url('media/images/flags/ja.png')
);
//how can I compare/replace them from here?
Thank you for help.

Rather than array you can do something like..
<img src="media/images/flags/<? echo $county; ?>.png" />

Use str_replace, get the search elements which are the country codes (keys) and the replacement values which are the flags (values)
$replace = array_values($flags);
$search = array_keys($flags);
$string = str_replace($search, $replace, $string)

$arr = func_get_args();
$num = func_num_args();
$keys = array();
$i = 0;
for($i=0;$i<$num;++$i){
$keys = array_merge($keys, array_keys($arr[$i]));
}
$keys = array_unique($keys);
$merged = array();
foreach($keys as $key){
$merged[$key] = array();
for($i=0;$i<$num;++$i){
$merged[$key][] = isset($arr[$i][$key])?$arr[$i][$key]:null;
}
}

Related

Merge combinations of values from a 2d array and form non-standard delimited strings

I have the following array:
$array = array
(
'firstname' => array('Daniel', 'John'),
'lastname' => array('Smith', 'Larsson')
);
I want to turn it into:
$array = array('firstname=daniel:lastname=smith',
'firstname=daniel:lastname=larsson',
'firstname=john:lastname=smith',
'firstname=john:lastname=larsson');
Of course the array can have more names and also have more fields other than "firstname" and "lastname".
What would be the most optimal way to solve this?
Something like the following should work:
function combine($fields) {
if (!count($fields)) return array('');
$values = reset($fields);
$field = key($fields);
array_shift($fields);
$suffixes = combine($fields);
$options = array();
foreach ($values as $value) {
$options = array_merge($options, array_map(function($suffix) use($field, $value) {
return "$field=$value:$suffix";
}, $suffixes));
}
return $options;
}
You will probably have to adjust it though (like remove extra : in the end).

How to reference cells with specific condition in php multidimensional array

I got an array like this:
$array[0][name] = "Axel";
$array[0][car] = "Pratzner";
$array[0][color] = "black";
$array[1][name] = "John";
$array[1][car] = "BMW";
$array[1][color] = "black";
$array[2][name] = "Peggy";
$array[2][car] = "VW";
$array[2][color] = "white";
I would like to do something like "get all names WHERE car = bmw AND color = white"
Could anyone give advice on how the PHP spell would look like?
function getWhiteBMWs($array) {
$result = array();
foreach ($array as $entry) {
if ($entry['car'] == 'bmw' && $entry['color'] == 'white')
$result[] = $entry;
}
return $result;
}
Edited: This is a more general solution:
// Filter an array using the given filter array
function multiFilter($array, $filters) {
$result = $array;
// Removes entries that don't pass the filter
$fn = function($entry, $index, $filter) {
$key = $filter['key'];
$value = $filter['value'];
$result = &$filter['array'];
if ($entry[$key] != $value)
unset($result[$index]);
};
foreach ($filters as $key => $value) {
// Pack the filter data to be passed into array_walk
$filter = array('key' => $key, 'value' => $value, 'array' => &$result);
// For every entry, run the function $fn and pass in the filter data
array_walk($result, $fn, $filter);
}
return array_values($result);
}
// Build a filter array - an entry passes this filter if every
// key in this array corresponds to the same value in the entry.
$filter = array('car' => 'BMW', 'color' => 'white');
// multiFilter searches $array, returning a result array that contains
// only the entries that pass the filter. In this case, only entries
// where $entry['car'] = 'BMW' AND $entry['color'] = 'white' will be
// returned.
$whiteBMWs = multiFilter($array, $filter);
Doing this in code is more or less emulating what a RDBMS is perfect for. Something like this would work:
function getNamesByCarAndColor($array,$color,$car) {
$matches = array();
foreach ($array as $entry) {
if($entry["color"]== $color && $entry["car"]==$car)
matches[] = $entry["name"];
}
return $matches;
}
This code would work well for smaller arrays, but as they got larger and larger it would be obvious that this isn't a great solution and an indexed solution would be much cleaner.

Assigning values to associative array with dynamic keys

I have $options as an associative array with each value as mixed(can be strings, or other arrays). I won't have any objects there.
$keys is a numeric array & the number of keys is determined at runtime.
I want to have a result similar to this expression
$options[$keys[0]][$keys[1]].......[$keys[count($keys)-1]] = $value;
For example, if $keys = array('key1'), i want to do
$options['key1'] = $value;
& if $keys = array('key1', 'key2'), i want to do
$options['key1']['key2'] = $value;
& so on
The problem with array_replace_recursive is that $value may itself be an array. Someway to constrain the depth to which array_replace_recursive can go? or maybe some other way?
I made something similar like this:
$options = array('key1' => array('key2' => array('key3' => 'value')));
$keys = array('key1', 'key2', 'key3');
$search = &$options;
foreach ($keys as $key) {
$search = &$search[$key];
}
$search = 'changed value';
var_dump($options);
You could always create references to the next key.
I think this is not possible, As array is a data structure and you can not put code or loop inside it. Let me google i will update you once i get some solution :)
I finally got it working. Thanks to #Benjamin Paap. His answer helped to get to the exact solution
$options = array('key1' => array('key2' => array('key3' => 'value')));
$keys = array('key1', 'key2', 'key3');
$length = count($keys);
$search = &$options;
foreach ($keys as $key => $value) {
// key doesn't exist or value is not an array
if(!isset($search[$value]) || !is_array($search)) {
$search = (array) $search;
$search[$value] = array();
}
$search = &$search[$value];
// last iteration
if($length - 1 === $key) {
$search = 'new value';
}
}
unset($search);
var_dump($options);

php foreach supplied argument not valid

I am getting results from a mysql table and putting each cell into an array as follows:
$sqlArray = mysql_query("SELECT id,firstName FROM members WHERE id='$id'");
while ($arrayRow = mysql_fetch_array($sqlArray)) {
$friendArray[] = array(
'id' => $arrayRow['id'],
'firstName' => $arrayRow['firstName'],
);
}
Then I do a search for a specific friend. For example if I want to search for a friend name Osman, i would type and o and it will return to me all the results that start with the letter o. Here is my code for that:
function array_multi_search($array, $index, $pattern, $invert = FALSE) {
$output = array();
if (is_array($array)) {
foreach($array as $i => $arr) {
// The index must exist and match the pattern
if (isset($arr[$index]) && (bool) $invert !== (bool) preg_match($pattern, $arr[$index])) {
$output[$i] = $arr;
}
}
}
return $output;
}
$filtered = array_multi_search($friendArray, 'firstName', '/^o/i');
and then it will print out all the results. My problem is that it returned an error saying "Invalid argument supplied to foreach()" and that is why I added the if(is_array)) condition. It is working fine if I leave this code in the index.php page, but I moved it to a subfolder named phpScripts and it doesn't work there. Any Help?
$output is not returning any value because apparently $friendArray is not an array. But I verified that it is by using print_r($friendArray) and it returns all the member's id and firstName.
P.S. I use JavaScript to the the call using AJAX.
If your array structure is such:
$friendArray[] = array(
'id' => $arrayRow['id'],
'firstName' => $arrayRow['firstName'],
);
This means your array is indexed and two levels.
So the correct way to walk through it is:
foreach($array as $cur_element) {
$id = $cur_element['id'];
$firstName = $cur_element['firstName'];
}
Change this:
foreach($array as $i => $arr) {
To this:
foreach((array)$array as $i => $arr) {
Are you sure that $array is not empty?

How to listSubscribe in Groups Mailchimp API 1.3

As the example below shows how to call on the fields, my question is how to call a multiple checked checkbox. please give me an example
$merge_vars = array('FNAME'=>'Test', 'LNAME'=>'Account',
'GROUPINGS'=>array(
array('name'=>'Your Interests:', 'groups'=>'Bananas,Apples'),
array('id'=>22, 'groups'=>'Trains'),
)
);
I get a solution for this.
To get the multiple checked checkbox you need to do a looping and set it in array then change the array to a string.
if(!empty($_POST['listbox']))
{
foreach($_POST['listbox'] as $value => $val)
{
$values[] = $val;
}
$groups = implode(",", $values);
}
then set it in the merge_vars
$merge_vars = array('FNAME'=>'Test', 'LNAME'=>'Account',
'GROUPINGS'=>array(
array('name'=>'Your Interests:', 'groups'=> $groups)
)
);
Hope it helps :)
You must put the separated by commas but you must ensure that they have commas escaped:
$groups = array();
if(!empty($_POST['listbox'])) {
$interests = array();
foreach($_POST['listbox'] as $interest)
{
$interests[] = str_replace(',', '\,', $interest);
}
$groups = implode(",", $interests);
}
$merge_vars = array(
'FNAME'=>'Test',
'LNAME'=>'Account',
'GROUPINGS'=> array(
array(
'name'=>'Your Interests:',
'groups'=> $groups
),
array(
'id'=>22,
'groups'=>'Trains'
)
)
);
If you are sure that the interest string do not have commas you can just do this:
$groups = implode(',', $_POST['listbox']);

Categories