I have an array like this
Array ( [12313] => 1 [12312] => 1 ) 1
The array keys are the items that exist in the warehouse and values are the number of items.
I would like to check if the items and amounts actually exist in the warehouse database using php. I thought maybe I could use a foreach for each item check but I don't know how to use foreach. I would like to make a query like:
$query=$this->db->query("SELECT COUNT(*) as amount FROM warehouse where item=12313");
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
$array=array ( '12313' => 1,'12312' => 1 );
foreach($array as $k=>$val)
{
$query=$this->db->query("SELECT COUNT(*) as amount FROM warehouse where item='".$k."'");
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
}
Are you looking for something like:
$items = array(
12313 => 1,
12312 => 1,
);
foreach ( $items as $key => $value ) : //iterate over array
$query = "SELECT COUNT(*) as amount FROM warehouse where item = $key";
$check = $query->row_array();
$amt = $check['amount'];
if( $amt>0 ) {
return true;
}
else {
return false;
}
endforeach;
try this
$arr = array("[12313]" => "1" ,"[12312]" => "2");
foreach ($arr as $key=>$value) {
$query="SELECT COUNT(*) as amount FROM warehouse where item='".$key."'";
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
}
$array = array('12313' => 1, '12312' => 1);
foreach ($array as $key => $value) {
$this->db->select('COUNT(*) as amount');
$this->db->from('warehouse');
$this->db->where('item', $key);
$result = $this->db->get()->row_array();
return ($result['amount'] >= $value) ? TRUE : FALSE; //match no of items
// return ($result['amount'] > 0) ? TRUE : FALSE; //OR if just check the count
}
Related
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);
}
I have multiple ID's in an mysql database. I would like to know if there are ID's in the database which are not present in an multi dimensional array. For each ID which is not present in the multi dimensional array the row needs te be deleted. The following code is what I have so far.
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ( ($element === $search_for) ) {
return true;
} elseif (is_array($element)) {
$result = multi_array_search($search_for, $element);
if($result == true)
return true;
}
}
return false;
}
$output = mysql_query("SELECT id FROM ads");
while ($g = mysql_fetch_array($output)) {
echo multi_array_search("$g", $arr) ? 'Found' : 'Not found';
}
I don't think the above code is correct for what I want?
Information:
The $arr looks like:
Array (
[0] => Array (
[url] => http://
[id] => 752
)
[1] => Array (
[url] => http://
[id] => 758
)
)
I tryed some solutions now and none of the mare working :(
Every thing seems to be fine. Just few updates to remove unwanted code from elseif and add one more check !empty into elseif condition.
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ($element === $search_for){
return true;
}elseif(is_array($element) && !empty($element)){
$result = multi_array_search($search_for, $element);
}
}
return false;
}
$output = mysql_query("SELECT id FROM ads");
while ($g = mysql_fetch_array($output)) {
echo multi_array_search("$g", $arr) ? 'Found' : 'Not found';
}
Hope will help!
$removeid=array();
$idarray is the multi dimensional array you want to check your database id with.
$result = 'store your databse id here in the form of an array';
foreach ($result as $key => $value) {
$result=$value;
if(!empty($result))
{
foreach ($idarray as $key => $value) {
if ($value["id"] != $result) {
$removeid=$key;
}
}
}
}
now $removeid contains the id to be removed from the databse
$un_array = array();
foreach ($array as $h) {
$id = $h['id'];
array_push($un_array, $id);
}
$db_array = array();
$output = mysql_query("SELECT id FROM account WHERE account='$username'");
while ($g = mysql_fetch_assoc($output)) {
$id = $g['id'];
array_push($db_array, $id);
}
$result = array_diff($db_array, $un_array);
foreach ($result as $r) {
mysql_query("DELETE FROM account WHERE id='$r'");
}
I have two array like
previous:
Array(
[name] => [asdfg]
[city] => [anand]
)
current:
Array(
[name] => [ud]
[state] => [anand]
)
Now i have to compare these two array and want to alter the changed current array key or values and wrap the elements like
Array(
[name] => [<span class='bold_view'> ud </span>]
[<span class='bold_view'> state </span>] => [anand]
)
$current['name']="<span class='bold_view'> ".$current['name']." </span>";
$current['<span class='bold_view'> state </span>']=$current['state'];
I have to say that it doesn't make much sense but here it is..
Copy this code and just execute : and see the view source (Ctrl+u)
<?php
$prev = array("name"=>"[asdfg]","city"=>"[anand]");
$curent = array("name"=>"[ud]","state"=>"[anand]");
$res = array();
foreach($prev as $key=>$val){
$res[$key] = $val;
if(array_key_exists($key,$curent)){
$res[$key] = "[<span class='bold_view'> ".$curent[$key]." </span>]";
}
if($new_key = array_search($val,$curent)){
unset($res[$key]);
$res["<span class='bold_view'> ".$new_key." </span>"] = $val;
}
}
print_r($res);
?>
$arr_pre = array(
"name"=>"asdfg",
"city"=>"anand",
"address" => "anand",
);
$arr_current= array(
"name"=>"ud",
"state"=>"anand",
"address" => "ananda"
);
$result = array_diff_assoc($arr_current,$arr_pre);
$count_curr = array_count_values($arr_current);
$count_old = array_count_values($arr_pre);
foreach ($result as $key => $value){
if(!array_key_exists($key,$arr_pre ))
{
$key_new = "<b>".$key."</b>";
if(!in_array($value,$arr_pre))
{
$val = "<b>".$value."</b>";
}
else if((isset($count_curr[$value]) != isset($count_old[$value])))
{
$val = "<b>".$value."</b>";
}
else
{
$val = $value;
}
unset($arr_current_info[$key]);
}
else {
$key_new = $key;
if(!in_array($value,$arr_pre))
{
$val = "<b>".$value."</b>";
}
else if((isset($count_curr[$value]) != isset($count_old[$value])))
{
$val = "<b>".$value."</b>";
}
else
{
$val = $value;
}
}
$arr_current_info[$key_new]=$val;
}
echo "<pre>";
print_r($arr_current_info);
I have done like this and i got perfect answer
I have a database table with a column where multiple strings are stored in each field, separated by a ;
I need to get a list of all unique values in that column. I know there has to be an easier way to do this, but I can't find my answer anywhere. Here is what I'm doing so far:
$result = mysql_query("SELECT DISTINCT column FROM modx_scripture_table WHERE column!=''", $con);
$filter_all = array();
while($row = mysql_fetch_array($result))
{
$filter_all[] = $row;
}
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
$filter_flat = array_flatten($filter_all);
function array_explode($array) {
$result = array();
foreach ($array as $key => $value) {
$result[$key] = explode(';',$value);
}
return $result;
}
$filter_sploded = array_explode($filter_flat);
$filter_full = array_flatten($filter_sploded);
$filter_final = array_unique($filter_full);
print_r($filter_final);
Everything seems to be working except the array_unique. I'm still getting duplicate strings in $filter_final. What am I doing wrong?
After exploding the string use array_unique() for fnding unique values in an array.
Example:
$arr=array('1','2','3','4','5','3','1');
print_r(array_unique($arr));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
I have an array of categories:
categories = computers, entertainment, products, graphics cards
The array is sometimes returned in the wrong order BUT each category has a parent which exists in the SAME array.
categories =
products[parent=0],
entertainment[parent=products],
computers[parent=entertainment],
graphics cards[parent=computers]
How would I use php to sort this array if it was returned in any order?
Unordered Example:
categories =
computers[parent=entertainment],
entertainment[parent=products],
products[parent=0],
graphics cards[parent=computers]
Must produce:
categories = products, entertainment, computers, graphics cards
Are you talking about a simple sort like this:
<?php
$categories = array('computers[parent=entertainment]',
'entertainment[parent=products]',
'products[parent=0]',
'graphics cards[parent=computers]');
sort($categories);
echo '<pre>';
print_r($categories);
echo '</pre>';
?>
Looking at your example, I'm assuming you want a topological sort, as Sam Dufel says.
$categories = array(
"computers" => array("parent" => "entertainment"),
"entertainment" => array("parent" => "products"),
"products" => array("parent" => null),
"graphics cards" => array("parent" => "computers")
);
// Set distances
foreach ($categories as $cat => &$e) {
$e["dist"] = nodeDistance($cat, $categories);
}
// Before
echo implode(", ", array_keys($categories)) . "\n";
// Sort
uasort($categories, "nodeDistanceSorter");
// After
echo implode(", ", array_keys($categories)) . "\n";
function nodeDistance($node, $categories) {
// Check cache
if (array_key_exists("dist", $categories[$node]))
return $categories[$node]["dist"];
// Check root
if (is_null($categories[$node]["parent"]))
return 0;
// Traverse
return nodeDistance($categories[$node]["parent"], $categories) + 1;
}
function nodeDistanceSorter($a, $b) {
$aDist = $a["dist"];
$bDist = $b["dist"];
if ($aDist == $bDist)
return 0;
return $aDist - $bDist;
}
categories =
products[parent=0],
entertainment[parent=products],
computers[parent=entertainment],
graphics cards[parent=computers]
I take it that the array is like this:
$categories = array
(
'products'=>array('parent'=>0),//poor little orphan
'entertainment'=>array('parent'=>'products'),
'computers'=>array('parent'=>'entertainment'),
'graphics cards'=>array('parent'=>'computers'),
)
here is a solution that I mixed up right now:
Solution 1
$categories = array
(
'computers'=>array('parent'=>'entertainment'),
'entertainment'=>array('parent'=>'products'),
'products'=>array('parent'=>0),
'graphics cards'=>array('parent'=>'computers')
);
function addparentfirst(&$original,$array,$name,$data){
if(isset($data['parent']) && isset($original[$data['parent']])){
$array = addparentfirst($original,$array,$data['parent'],$original[$data['parent']]);
}
$array[$name] = $data;
unset($original[$name]);
return $array;
}
foreach($categories as $key=>$value){//goes over each category only once, contrary to what it looks like
$sortedcategories = addparentfirst($categories,$sortedcategories,$key,$value);
}
$categories = $sortedcategories;//NOW IT'S SORTED
print_r($categories);
Solution 2
//It's interesting that it doesn't loop infinitely
//I like this solution the most
function addparentfirst(&$array,$key){
if(isset($array[$key]['parent']) && !empty($array[$key]['parent'])){
addparentfirst($array,$array[$key]['parent']);
}
$data = $array[$key];
unset($array[$key]);
$array[$key] = $data;
return $array;
}
foreach($categories as $key=>$value){
addparentfirst($categories,$key);
}
print_r($categories);
Solution 3
function sortArrayByArray($array,$orderArray) {
$ordered = array();
foreach($orderArray as $key) {
if(isset($array[$key])) {
$ordered[$key] = $array[$key];
unset($array[$key]);
}
}
return $ordered + $array;
}
//Usage:
$categories = sortArrayByArray($categories,array('products','entertainment','computers','graphics cards'));
print_r($categories);
as seen here
Solution 4
function get_childless_category_name($array){
foreach($array as $key=>$value){
if(isset($value['parent']) && !empty($value['parent'])){
unset($array[$value['parent']]);
}
}
$names = array_keys($array);//names of all the child free categories
return array_pop($names);//get the last one (there should only be one)
}
function parent_comes_first(&$array,$key){
if(isset($array[$key]['parent']) && !empty($array[$key]['parent'])){
$array = parent_comes_first($array,$array[$key]['parent']);
}
$data = $array[$key];
unset($array[$key]);
$array[$key] = $data;
return $array;
}
//Usage:
$childless = get_childless_category_name($categories);
parent_comes_first($categories,$childless);
print_r($categories);