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
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);
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.
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 have two arrays, what consist arrays. I need to merge these arrays recursive. But I need to do this action few times, and
array_merge_recursive()
will apend my data twice, I want to remove element what already exist in target array.
$messages array :
array(2) {
["messages"]=>
array(2) {
["test.testik"]=>
string(13) "Це тест"
["test2313.tes31231tik"]=>
string(23) "це тестончик"
}
["validators"]=>
array(4) {
["valid.validik"]=>
string(36) "Це валідне значення"
["joga.jimbo"]=>
string(27) "Джімбо торбінс"
["validka.invalidka"]=>
string(23) "це інвалідка"
["smith.john"]=>
string(17) "джон сміт"
}
}
$allCar array:
array(2) {
["messages"]=>
array(1) {
["test2313.tes31231tik"]=>
string(23) "це тестончик"
}
["validators"]=>
array(2) {
["validka.invalidka"]=>
string(23) "це інвалідка"
["smith.john"]=>
string(17) "джон сміт"
}
}
I wrote some code:
foreach ($messages as $domain => $messagesArray) {
foreach ($allCat as $d => $mess) {
if ($domain == $d) {
foreach ($messagesArray as $ymlkey => $trans) {
foreach ($mess as $ymlk => $transl) {
if ($ymlkey == $ymlk) {
unset($mess[$ymlk]);
}
}
}
}
}
}
Then when I run recursive merge it append the same values to array. What I am doing wrong ?
This:
foreach ($allCat as $d => $mess) {
$mess is a temporary COPY of whatever value your foreach() loop is currently working on. When you do your unset($mess...) later on, you're simply unsetting that temporary copy.
While some might suggest making $mess a reference, this can/will cause problems later on, because $mess will STILL be a reference after the loops end, and reusing the variable later on will now be mucking around with whatever $mess last pointed at in the loop.
Instead, use the full array/object path reference in the unset call:
unset($messages[$domain][$d][$ymlkey][$ymkl])
or whatever it should be. This way you guarantee you're working with the actual "real" array, and not any of the many temporary copies your nested loops are creating.
I am still very new to PHP and from all the examples that are around they all seem to use foreach statements.
e.g.
foreach ($variable as $row)
However I don't think I should be using this all the time, for example variables or objects I have an which only has one row or instance in an array.
I know its advantageous to use them for multiple rows which could be missed if you used a for loop.
But do I really need to use it just to echo one variable thats in an array?
e.g. for example this variable $stats
array(3) { ["user_interventions"]=> int(4) ["fastest_intervention"]=> array(1) { [0]=> object(stdClass)#22 (1) { ["duration"]=> string(8) "02:10:00" } } ["slowest_intervention"]=> array(1) { [0]=> object(stdClass)#23 (1) { ["duration"]=> string(8) "02:26:00" } } }
Thanks
if you know the 'address' of the value in your array, then there's no need for a loop:
echo $arr['user_interventions'][0]['duration']; // 02:10:00
More details here.
No, you do not need to use a foreach loop every time you need to access an array value. Your example could be used in the following manner...
echo $stats['fastest_intervention']['0']->duration; // Outputs: 02:10:00
Here's your variable dump with indentation (makes it easier to read).
array(3) {
["user_interventions"]=> int(4)
["fastest_intervention"]=> array(1) {
[0]=> object(stdClass)#22 (1) {
["duration"]=> string(8) "02:10:00"
}
}
["slowest_intervention"]=> array(1) {
[0]=> object(stdClass)#23 (1) {
["duration"]=> string(8) "02:26:00"
}
}
}
You need not to use foreach here but you can't just print $array
if you indexes of array you may print something like:
print 'Key is '.$array['key'].' but index is only'.$array['index'];
You just access the variables using []. print $array['key']