John Davidson

PHP array loop - unable to access elements

0 comments
Message:


I have an array.
It comes from this query:


$table_array=array();
$table_array = $mydb->get_results($mydb->prepare("SELECT sid, stitle FROM tablename"));

I successfully retrieve the data. The console shows the json_encode returns via ajax (success function):


function align_surveys(){
jQuery.ajax({
type: 'POST',
url: MyAjax.ajaxurl,
data: {"action": "align_sids"},
success:
function(data){
console.log('data: '+ data)
}
});
}

"data:":[{"sid":"525331","stitle":"First Title"},{"sid":"367775","stitle":"Second Title"}]

However, when I run a foreach loop, I get a 500 error when I try to access it's elements.


This errors:


foreach($table_array as $row){
$s_ids[] = $row[0];
}

And, this errors:


foreach($table_array as $row){
$s_ids[] = $row['sid'];
}

gettype tells me this is in fact an array. But, anytime I reference the array element, I error out. I cannot solve it. Is it something to do with extra curly braces inside the square brackets? Anyone, please, point me in the right direction. Been hours....


UPDATE:
print_r show me this:


Array ( [0] => Array ( [surveyls_survey_id] => 525331 [0] => 525331 [surveyls_title] => New Survey [1] => New Survey ) [1] => Array ( [surveyls_survey_id] => 367775 [0] => 367775 [surveyls_title] => Second Survey [1] => Second Survey ) )

This looks to me like it's an array of arrays where the keys are actually the values...Not sure how or why this is the result I am getting.



My Answer:
>get_results("SELECT * FROM my_table");

_I want to loop through the array and access each element, but I am having trouble accessing the elements._

Here is an example of how you can loop through the array and access each element:

php
foreach ($table_array as $row) {
echo $row->column_name;
}


In this example, `$row` represents each row in the array, and `column_name` is the name of the column you want to access in each row. You can replace `column_name` with the actual column name you want to access.

If you are still having trouble accessing the elements in the array, please provide more information about the structure of the array and how you are trying to access the elements.

Rate this post

3 of 5 based on 4986 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us