So I'm using a foreach cycle like this:
foreach($cats_arr as $category) {
$options_arr[$category->name] = false;
}
and when I var_dump($options_arr['Articles']) it comes out like this, so I assume that I'm building the array properly:
bool(false) string(1) "5"
Next, I need to assign that array as a value of a key-value pair in another array, and then it breaks. I'm doing it like this:
$admin_options = array(
"cats" => $options_arr
);
So I can access the array with $admin_options['cats'], but how to I access the array's keys that's assigned to the "cats" key?
EDIT: Here's what comes out when I var_dump($admin_options['cats'])
array(1) { [0]=> array(4) { ["Articles"]=> bool(false) ["Blog Posts"]=> bool(false) ["News"]=> bool(false) ["Uncategorized"]=> bool(false) } }
Your $options_arr contains multiple keys, so you will have to either specify the key or use a foreach loop:
// Echo first key
echo $admin_options['cats'][0]['Articles'];
// Or this for all the keys
foreach($admin_options['cats'] as $cat) {
echo $cat['Articles'];
}
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'];
}
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 am trying to return the ids of each array in my session cart however at the moment it is not working correctly because i am only returning the position of the array which is not working when i go to remove the item from the array.
So how can i return the actual id of the array code below:
Current Array:
$_SESSION['cart'] = array(1) {
[1]=>
array(3) {
["start"]=>
string(18) "name"
["end"]=>
string(19) "name"
["amount"]=>
string(2) "11"
}
}
From the above i am trying to retrieve 1 from [1]=> where later i will use to delete the array using $_SESSION['cart'][$arrayId];
for now i am counting the loops in the array using $i but this is insufficient.
So to reiterate i am trying to return the "[1]" id from [1]=>, unless there is another method that is better i would be all ears :)
Hope this makes sense everyone.
Alex
Addtional info:
Lets say i am inside the loop at the moment, can i somehow call the id from inside the foreach loop?
To iterate over an array's keys and values, use foreach:
foreach ($_SESSION['cart'] as $key => $value) {
if ($value/* something */) {
echo $key;
}
}
array_keys() is what you need.
If you just need the id of a row in the array, you can do the following:
foreach ($_SESSION['cart'] as $id => $array) {
echo $id; // $id will be the value of the keys of the looped array.
}
$ids = array_keys($_SESSION['cart']);
I have a $date array like this:
[1]=> array(11) {
["meetingname"]=> string(33) "win2008connectcurrent0423131"
[0]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
[1]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 14:40:06"
["numparticipants"]=> string(1) "3"
}
}
foreach($date[0] as $key => $meetings){
print "$key = $meetings\n";////yields scoid = 3557012
}
And, as you can see above, I am looping over individual elements. The first element (not indexed) is always meetingname; the rest of the elements are indexed and themselves contain arrays with three elements in each array--in the above code they are [0] and [1].
What I need to do is make the $meetings as an array containing [0] and then [1] etc, depending on the number of elements. So essentially, the output for print should be an array (I can also use var_dump) with key/values of [0] but right not it only outputs individual keys and their values, for example, as you can see above, scoid=3557012. I will need, something all keys/values in the $meetings variable, something like:
{
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
How can I fix the foreach loop for that?
please Try this. hope it help.
foreach($date as $key => $meetings){
if($key == "meetingname")
continue;
else
print "$meetings\n";
}
You can just create a new array and add the meetings to that one
<?php
$meetings = array();
foreach($date[1] as $key=>$meeting) {
if (!is_int($key))
continue; //only handle numeric keys, incase you ever change the name of the first key 'meetingname'
$meetings[] = $meeting
}
var_dump($meetings);
?>