Check is a string element of CodeIgniter query - php

Hello I wanna check if is string element of codeIgniter query, so I wanna compere to arrays.
I use this soulution but i get false in both case.
$data = array(
'Firstname' => $ime ,
'Lastname' => $prezime,
'Nick' => $username,
'EmailAddress' => $email,
'Uid' => $uid,
);
$rs = $this->db->query("Select Nick FROM cms_cart_customers");
$array = $rs->result_array();
if(!in_array($data['Nick'],$array))
{
$this->db->insert('cms_cart_customers', $data);
}

The result_array() function returns you a multi-dimensional array, even with a single column. You need to flatten the array in order to search the array linearly, try something like this:
$array = $rs->result_array();
$flattened = array();
foreach($array as $a) {
$flattened[] = $a['Nick'];
}
if(!in_array($data['Nick'],$flattened)) {
$this->db->insert('cms_cart_customers', $data);
}

Codeigniter query will return result in associative array and in_array() function will not going to do the trick.
Here is one way you can do this custom is_in_array function source
//Helper function
function is_in_array($array, $key, $key_value){
$within_array = false;
foreach( $array as $k=>$v ){
if( is_array($v) ){
$within_array = is_in_array($v, $key, $key_value);
if( $within_array == true ){
break;
}
} else {
if( $v == $key_value && $k == $key ){
$within_array = true;
break;
}
}
}
return $within_array;
}
$array = $rs->result_array();
if(!is_in_array($array, 'Nick', $data['Nick']))
{
$this->db->insert('cms_cart_customers', $data);
}
Other Method
If you are trying to avoid duplicate entry, you should use a Select query first to check that the 'Nick' = $username is already present in table, if not then Issue an insert
Example
$rs = $this->db->get_where('cms_cart_customers', array('Nick' => $username));
//After that just check the row count it should return 0
if($rs->num_rows() == 0) {
$this->db->insert('cms_cart_customers', $data);
}

Related

How to get data from database that result as an array in model codeigniter

I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}

PHP - Find Specific Value in Array (multidimensional)

I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?

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.

How to make first array value to uppercase

I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);
but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )
And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
Main MY_Model method
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);
If Its not, then $data array have only read attribute.
The array_from_post() method returns an array with the format below:
$data = array(
'position' => 'it',
'label' => 'Information Technology'
);
So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
static $i = 0;
if ($i === 0) { $i++; return strtoupper($a); }
else return $a;
}, $array);
Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
static $i = 0;
if ($i == 0) { $i++; $value = strtoupper($value); }
});
Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.

PHP Dynamic array key [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Dynamic array keys
I have an array $Values
which is set up like this
$Values
1
2
3
a
b
c
4
which is nested.
and I have a key like this: $key = "a"]["b"]["c";
Can I now do: Values[$key], ti get the value in c ?
#Edit
Simply said: I want to get the value from array $Values["a"]["b"]["c"] By doing $Values[$key]. What should my key be then?
No, but you can extract the result:
$Values = array( '1' => 'ONE',
'2' => 'TWO',
'3' => 'THREE',
'a' => array( 'b' => array( 'c' => 'alphabet') ),
'4' => 'FOUR'
);
$key = '"a"]["b"]["c"';
$nestedKey = explode('][',$key);
$searchArray = $Values;
foreach($nestedKey as $nestedKeyValue) {
$searchArray = $searchArray[trim($nestedKeyValue,'"')];
}
var_dump($searchArray);
Will only work if $key is valid.
Now how do you get in a situation with a key like this anyway? Perhaps if you explained the real problem, we could give you a real answer rather than a hack.
No, you only can get individual keys from variables. Depending on what you really want to do you could use references to your array elements.
Nah you can't. This is invalid syntax.
Hover you can do:
$key = 'a,b,c';
// or:
$key = serialize( array( 'a','b', 'c'));
// or many other things
And than implement your array-like class which will implement ArrayAccess or ArrayObject (let's way you'll stick with $key = 'a,b,c';):
class MyArray extends ArrayAccess {
protected $data = array();
protected &_qetViaKey( $key, &$exists, $createOnNonExisting = false){
// Parse keys
$keys = array();
if( strpos( $key, ',') === false){
$keys[] = $key;
} else {
$keys = explode( ',', $key);
}
// Prepare variables
static $null = null;
$null = null;
$exists = true;
// Browse them
$progress = &$this->data;
foreach( $keys as $key){
if( is_array( $progress)){
if( isset( $progress[ $key])){
$progress = $progress[ $key];
} else {
if( $createOnNonExisting){
$progress[ $key] = array();
$progress = $progress[ $key];
} else {
$exists = false;
break;
}
}
} else {
throw new Exception( '$item[a,b] was already set to scalar');
}
}
if( $exists){
return $progress;
}
return $null;
}
public offsetExists( $key){
$exists = false;
$this->_getViaKey( $key, $exists, false);
return $exists;
}
// See that we aren't using reference anymore in return
public offsetGet( $key){
$exists = false;
$value = $this->_getViaKey( $key, $exists, false);
if( !$exists){
trigger_error( ... NOTICE ...);
}
return $value;
}
public offsetSet ( $key, $val){
$exists = false;
$value = $this->_getViaKey( $key, $exists, true);
$value = $val;
}
}
// And use it as:
$array = MyArray();
$array['a']['b']['c'] = 3;
$array['a,b,c'] = 3;
Or implement function:
public function &getArrayAtKey( $array, $key){
// Similar to _qetViaKey
// Implement your own non existing key handling
}

Categories