i build an array from mysql this way
$q="select account_code from chart_master;";
// Generate resultset
$result_set = $con->query($q);
$list = Array();
while( $myrow = mysqli_fetch_array($result_set) ) {
$list[] = $myrow;
}
when i dump $list i get:
array(79) { [0]=> array(2) { [0]=> string(8) "11011001" ["account_code"]=> string(8) "11011001" } [1]=> array(2) { [0]=> string(8) "11011002" ["account_code"]=> string(8) "11011002" } [2]=> array(2) { [0]=> string(8) "11011005" ["account_code"]=> string(8) "11011005" } ...
i now want to check if a value is found in the values 11011001, 11011002 etc with this code:
if (in_array($row['1'], $list))
{
echo $row['1']." found in the array";
}
with $row['1'] being one of the searched value.
I guess I am not looking at the right depth in the array because my in_array does not return anything.
Thoughts?
You should go through each element of your $list array and apply in_array to it.
foreach($list as $listItem){
if(in_array($row['1'], $listItem)){
echo $row['1']." found in the array";
}
}
in_array() only checks one dimension. That's why you need to go iterate through the first dimension and apply it to the second one.
The most succinct version of this I can imagine would be:
$exists = array_search('1001010101', array_column($list, 'account_code')) !== false;
This grabs the account_code column from the multidimensional array and looks inside that column for the value provided. If you only need an existence check, this seems to be a fast way of doing it.
However, if you don't need the rest of that SQL result set, I'd look into maybe doing a COUNT() or using a WHERE to narrow the result set instead. That would be more resource efficient.
Related
I have two array and want to merge it by using key of main array;
// $result : main dataset (multidimensional array)
// $referenceData : data related with main dataset and want to merge it into main dataset (multidimensional array)
if ($result) {
foreach ($result as $key => $val) {
foreach ($referenceData[$val['id']] as $refKey => $refVal) {
$result[$key][$refKey] = $refVal;
}
}
}
The thing is, when the result is high (even for 1000 elements on each) it takes more than 5-10 seconds which is quite unexpected for me.
I tried to use array_merge and array_merge_recursive instead of two foreach but I kept failing. Is there any way I could improve the logic? Thanks in advance.
Edit (added sample array);
result :
array(1) {
[0]=>
array(6) {
["id"]=>
string(5) "13020"
["name"]=>
string(23) "Data Stream 1"
["rank"]=>
string(1) "3"
["data_1"]=>
string(2) "63"
["data_2"]=>
string(2) "256"
["data_3"]=>
string(3) "469"
}
}
referenceData:
array(1) {
[13020]=>
array(5) {
["percent"]=>
float(20.987654320988)
["count_min"]=>
string(1) "1"
["count_max"]=>
int(2)
["checked"]=>
bool(false)
["cond_id"]=>
string(1) "0"
}
}
You need to make the first array structure exactly like the second array so that you can easily merge them. To do so you can do like below : (Its a reference code, you need to change it at your end)
$rows = $db->table('<table name>')->get()->getResultArray();
$result = [];
foreach ($rows as $row) {
$result[$row['id']] = $row;
}
Once both arrays have a similar structure, then you can go for a single foreach() and + operator to combine child arrays.
$finalArray = [];
foreach($result as $key=>$value){
$finalArray[$key] = $value+$referenceData[$key];
}
print_r($finalArray);
Output: https://3v4l.org/qBa4V
Note: if you want to re-index this new array (in case you want indexes like 0,1,2... so on) then you can do:
$finalArray = array_values($finalArray);
This question already has answers here:
How to check if a specific value exists at a specific key in any subarray of a multidimensional array?
(17 answers)
Closed 4 years ago.
array(7) {
[0]=>
array(2) {
["name"]=>
string(14) "form[username]"
["value"]=>
string(1) "1"
}
[1]=>
array(2) {
["name"]=>
string(15) "form[is_active]"
["value"]=>
string(1) "1"
}
[2]=>
array(2) {
["name"]=>
string(8) "form[id]"
["value"]=>
string(1) "9"
}
}
I want to get the id from an array. The output I like to achive is 9.
My approach:
echo $array['form[id]'];
But I don't get an output.
When you use $array['form[id]']; you are looking for the key called 'form[id]' which will not work because the keys of your array are 0, 1 and 2. You can get your desired value by using $array[2]['value']. However this will always call the 2nd element of your array, which might not be what you want. A more dynamic solution would be something like this:
foreach ($array as $element) {
if ($element['name'] == 'form[id]') {
echo $element['value'];
break;
}
}
This will loop through your whole array and check the names of each element. Then when it matches your desired name it will print the value for that exact element.
The easiest way might be to just first re-index the array using array_column. Then you can use the name field as the key:
$array = array_column($array, null, 'name');
echo $arr['form[id]']['value'];
// 9
See https://3v4l.org/L1gLR
You could use a foreach and check for the content .. but the content for index 'name' is just a string form[id]
anyway
foreach( $myArray AS $key => $value){
if ($value['name'] == 'form[id]' ) {
echo $key;
echo $value;
}
}
You are trying to get the value as if it's an associative array (sometimes called a dictionary or map), however it's a plain or indexed array.
Get the value you want by calling $array[2]["value"]
You can also use some of the higher level functions such as array_search; then you could use:
$id = array_search(function($values) {
return $values['name'] == 'form[id]';
}, $array)["value"];
So I think you need to filter the array to find the element you need first, then output that element's value:
$filtered_array = array_filter($your_array, function(element){
return element['name'] == 'form[username]';
});
if (!empty($filtered_array)) {
echo array_pop($filtered_array)['value'];
}
pls, i would like to get the values of the $aa variable, i'm using the mysqli_fetch_all because all the values need to be used in another layer.
Thanks
$aa = mysqli_fetch_all($ttt,MYSQLI_ASSOC);
Output with var_dump($aa):
array(2) { [0]=> array(1) { ["followe"]=> string(8) "bammyww " } [1]=> array(1) { ["followe"]=> string(5) "demo " } }
i have tried using $aa['followe'] , but i'm getting invalid index error.
Just loop through it. It's an array containing associative arrays.
foreach($aa as $item)
{
$item['followe'] // do something with this.
}
Instead of $aa['followe'], try:
$aa[0]['followe'];
as its a multi-dimension array. And the right approach to get all the array element is using foreach() like:
foreach($aa as $item)
{
$item['followe']
}
use
$aa[0]['followe'];
$aa[0] is array(1) { ["followe"]=> string(8) "bammyww " }
$aa[0]['followe'] is string(8) "bammyww "
You can also use array_column as
array_column($aa,'followe');//retrieves values associated with the key followe
I pull a list of permissions from a the DB using and put them into an array;
while($row = mysql_fetch_assoc($get_permissions)) {
$_SESSION['permissions'][] = $row;
}
The contents of the session variable then looks like this;
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
below is the output using print_r instead which makes it easier to read.
Array ( [0] => Array ( [permission_name] => acl_assets_read ) [1] => Array ( [permission_name] => acl_assets_write ) )
I've read about using array_search and think it should work. I've tried to use the following to search for a permission;
if (array_search('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
The problem i have is that even though the result is there, it keep returning false. The syntax looks correct to me.
Your problem is that you add the entire row (which is an array of its own) from your database into the $_SESSION['permissions']-array, forming a sub-array for each time it iterates the values from the database.
This means that all values in $_SESSION['permissions'] are arrays, not strings. This in turn means that you cannot search for a string like that.
If you have stored the values you are interested in, in a column named permissions in the database, you simply need to add that element only to your $_SESSION['permissions']-array, like this
$_SESSION['permissions'][] = $row['permissions'];
This will add the string from that row into an element in the array $_SESSION['permissions'].
It's also worth noting that array_search() returns the key of the array, where as the first element will have an index (key) equal to 0. This means that the very first element of your array would really look like if (0) { /* code */ }. This will return to false (if (0) == false), so you should perhaps look into using ìn_array(), which returns a boolean true/false.
if (in_array('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
Also, mysql_* functions are deprecated, and you shoud stop using them if you can.
array_search will work for you but you need the proper array to search.
Take a look at this:
$arrOne = array("one", "two");
$arrTwo = array(array("one"), array("two"));
$key = array_search("one", $arrOne);
var_dump($key); // int(0) is the index of where the value was found
$key = array_search("two", $arrTwo);
var_dump($key); // bool(false) because "two" != array("one") or array("two")
Notice that the second array_search will return false because a string does not equal an array.
If you had:
array(2) {
[0]=> string(15) "acl_assets_read"
[1]=> string(16) "acl_assets_write"
}
instead of:
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
then your array_search would find the proper string
Here is your answer :
$userdb = array(array("permission_name" => 'acl_assets_read'),array("permission_name" => 'acl_assets_write'));
$key = array_search("acl_assets_write", array_column($userdb, 'permission_name'));
if($key != ''){
echo 'true';
}
If needle found $key show key of needle. If needle is not found $key show blank.
I have an array stored in $_SESSION:
var_dump($_SESSION['session_article']);
//result:
array(2) {
[0]=> array(2) {
["id"]=> string(1) "3"
["amount"]=> int(2)
}
[1]=> array(2) {
["id"]=> string(2) "13"
["amount"]=> int(1)
}
}
If I do:
for($artKey = 0;$artKey < count($_SESSION['session_article']);$artKey++){
$cartArt = $_SESSION['session_article'][$artKey];
//stuff that doesn't affect key or value
}
everything is fine ...but if I do:
foreach($_SESSION['session_article'] as $artKey => $cartArt){
//stuff that doesn't affect key or value
}
the page won't stop to load (infinite loading, like the foreach never terminates)
I would like to you know that the computer is not a dumb machine, so whenever you do not get the right result then its not the computers problem, it is in how you code.
So lets take a look at your code first you var_dump($_SESSION['session_article']) you got an array with two elements each being an associative array. Now observe that this is an array of arrays so you code in scenario 2 is wrong.
If it were to be just a single array say $myArray = ['Simon', 'Peter', 'You'] then this woul have worked fine (note I used the short array syntax here you can use array() if you prefer). But the problem is you have multidimensional Arrays so you could should be
foreach($_SESSION['session_article'], list($a,))
{
//stuffs here
}
or better walk through the $_SESSION['session_article'] as an associative array like so
$myArray = $_SESSION['session_article']
$field = count($myArray, COUNT_RECURSIVE - (int)2)
for ($record = 0; $record < $myArray.length; $record++) {
//record number
for ($field = 0; $field < $field ; $field++) {
//combine record and field here
}
}
Hope I could lend a helping hand?
Please checkout
http://php.net/manual/en/function.count.php
http://php.net/manual/en/control-structures.foreach.php
They really have a good doc, just take you time.