PHP in_array() not finding value [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
in_array() and multidimensional array
Got the following array returned from a database using this code:
$skus = array();
$result = mysql_query($sql);
if($result){
while($rows = mysql_fetch_array($result)){
$skus[]=$rows;
}
}
Results:
Array (
[0] => Array {
[0] => PUBELI
[group_sku] => PUBELI
)
[1] => Array (
[0] => PUBESSENTIALS
[group_sku] => PUBESSENTIALS
)
[2] => Array (
[0] => PUBMGRPROGROUPED
[group_sku] => PUBMGRPROGROUPED
)
[3] => Array (
[0] => PUB25GROUPED
[group_sku] => PUB25GROUPED
)
)
I'm looking for this value using in_array:
if (in_array('PUBESSENTIALS', $skus))
and it returns false. Am I doing this correctly?
Why would the array values not be enclosed in quotes if the values in the DB are strings?

Don't use PHP if you may do something with MySql!
Try this solution:
$sql = "SELECT * FROM table WHERE str = 'PUBESSENTIALS'"; // some query just add WHERE
$result = mysql_query($sql);
if($result) $Row = mysql_fetch_array($result)

Assuming $skus is the full array shown above, then 'PUBESSENTIALS' would not be in $skus, because $sku's contains child arrays.
However, in_array('PUBESSENTIALS', $skus[1]) would return true.
try looping through each $skus element, and then checking that child element for in_array(value, childArray)

You are only looking into the first array, and not any other array. You should look through each to test every sub-array. Something like this could do the job:
foreach($skus as $sku) {
if (in_array('PUBESSENTIALS', $sku)) {
return true;
}
}

Related

How do I access each value in array? [duplicate]

This question already has answers here:
how to extract a column from mysql result set?
(2 answers)
Closed 5 months ago.
I have attempted numerous times trying access each value in a array. The array contains the database results retrieved from the select query.
$query = DB::getInstance()->query("SELECT orderStatus FROM customerOrders");
foreach ($query->results() as $orderered) {
$result_array = array($orderered);
//print_r($result_array);
$orderData = array_map(function ($object) { return $object->orderStatus; }, $result_array);
$test = json_decode(json_encode($result_array), true);
$ORvalue = serialize($test);
$ORvalue2 = unserialize($ORvalue);
$orderValueNEW = call_user_func_array('array_merge', $ORvalue2);
print_r($orderValueNEW);//debug
}//close foreach loop
Result it prints are:
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 1 )
Array ( [orderStatus] => 1 )
What you're doing should work to retrieve each row, but if you want to access the orderStatus value, you can do this with your result array:
foreach ($result_array as $resultRow) {
echo $resultRow['orderStatus'];
}
That should work, if that's what you mean. If you want to access the orderStatus value in the first loop, you can refer to it as $row['orderStatus']. Or, if you do a SELECT * in your query and you want to go through all values from the query, you can just make another loop like foreach ($row as $column => value) { ... }
Are you looking to just print the values and not the associate key/value pairs?
Changing
$result_array[] = $row;
to
$result_array[] = $row['orderStatus'];
should do the trick.

how read multiple date values in PHP array and then subtract them, returning an int value

I have a task that I need to implement, in a nutshell I want to be able to read multiple date values from a table in mySQL using PHP then manipulate these values to get date difference in days, save these new days (int values) into another array for further manipulation (linear regression). My problem is I cant get to the point where I can save initial values retrieved from the DB into an array, but when I try to manipulate these values and save them into a second array, it does not work. here is my simple code:
$result = mysql_query("SELECT TO_DAYS(date) FROM ordering WHERE id=1",$conn);
$num_rows = mysql_num_rows($result);
// mysql_query($result,$conn) or die(mysql_error();
//echo $num_rows;
$data = array();
$days=array();
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$data[] = $row; // add the row in to the results (data) array
}
print_r($data); // print result
//This part is not working
for ($x=$num_rows;$x>0;$x--){
$days[x]=(($data[$x])-($data[$x-1]));
}
print_r($days);
mysql_close($conn);
If I don't include the for loop in my code, I get an output on the screen as follows:
Array (
[0] => Array ( [TO_DAYS(date)] => 735599 )
[1] => Array ( [TO_DAYS(date)] => 735630 )
[2] => Array ( [TO_DAYS(date)] => 735658 )
[3] => Array ( [TO_DAYS(date)] => 735689 )
[4] => Array ( [TO_DAYS(date)] => 735735 )
[5] => Array ( [TO_DAYS(date)] => 735780 )
[6] => Array ( [TO_DAYS(date)] => 735811 )
)
Please I really need some help here.
Thank You - Hamood
Try this:
for ($x = $num_rows - 1; $x > 0; $x--) {
$days[$x] = $data[$x]['TO_DAYS(date)'] - $data[$x-1]['TO_DAYS(date)'];
}
Here, $data[$x] is an array itself with key TO_DAYS(date), so you need to get your desired value with $data[$x]['TO_DAYS(date)'].

Add to an array while in a loop with a key [duplicate]

This question already has answers here:
PHP - Append elements to array
(3 answers)
Closed 8 years ago.
I'm trying to populate all the links in my database into an array with a key something like this:
$link = array(99999 => "http://link1.com", 111111 => "http://link2.com");
Which returns:
Array ( [99999] => http://link1.com [111111] => http://link2.com )
How can i get the array to look like that when going through a loop, Here is my code:
while($row = mysql_fetch_array($query)) {
$link[] = "$row[r_id] => $row[r_link]";
}
It returns:
Array ( [0] => 24004 => http://link1.com [1] => 30554 =>
http://link2.com
But i don't wan't it to be like this, How can i get it the same as the first example while going through a loop ?
while($row = mysql_fetch_array($query)) {
$link[$row['r_id']] = $row['r_link'];
}
$link[$row['r_id']] = $row['r_link'];

remove same values from an array [duplicate]

This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys

Search MultiDimensional Array For String & Get the key

I am using the PDO Api, and using the fetchAll() returns a Multiple Dimensional Array; This snippet below is just a test scenario; I just want to know if it's possible.
$LeUsername = "BravoSlayer";
$sth = $dbh->prepare("SELECT * FROM users WHERE Username='$LeUsername'");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
$ArraySearch = search_array($result, $LeUsername);
Output is as below:
Array ( [0] => Array ( [ID] => 1 [0] => 1 [Username] => bravoslayer [1] => bravoslayer [Password] => thisisatest [2] => thisisatest ) )
I want to search through the multi-dimensional array to return the key. IN this case it will be 0 so I can just associate another variable variable for $Array1 = $Array1['0'] so from then I can do:
$Username = $Array1['Username'];
Judging by your question. You could search the primary array within a foreach loop and use in_array to return the correct array.
Use this as your reference.
function Search_Array($Array, $SearchDilema)
{
foreach ($Array AS $CheckKeys)
{
if (in_array($SearchDilema, $CheckKeys))
{
return $CheckKeys;
}
else
{
$ErrorMsg = "No Results Found! Check Your Search Dilema";
return $ErrorMsg;
}
}
}

Categories