Why do i get array foreach loop? - php

Hello can someone explain me why i'm getting an array in this code?
$loop2 = $link->query("SHOW tables FROM test");
$tables = $loop2->fetchAll(PDO::FETCH_ASSOC);
foreach($tables as $table) {
$capital = $table;
$small = $table;
when i echo $capital or $small i get (Array) why is that? i'm using foreach by the way sorry i'm a newbie

I thinks, It's a associative array, please try print_r to check the associative and then use another one foreach loop and try again.
$kmg = array('val1'=>array('1','2','3'),
'val2'=>array('4','5','6'));
foreach($kmg as $value){
print_r($value);
}

In the loop $table is an associative array which contain items (table columns names) from your selected table, like as below
$table['column_id'];
$table['column_name'];
$table['column_date'];
You can further check it columns by using print_r() php function
print_r($table);

Related

How to loop mysql result inside an array

I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?
You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO
You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);

foreach result only first letters of each row

Im getting the array from a function then using it on a foreach, it prints all rows, how can i print specific row when im using [0] after array it displays only first letters of both rows.
PHP FUNCTION:
public function selectedOffer($model_id){
$qq = mysqli_query($this->connection,"SELECT offerId FROM offers WHERE model_id='$model_id' ORDER BY id ASC");
$results = array();
while ($result = mysqli_fetch_array($qq)) {
$results[] = $result;
}
return $results;
}
FOREACH PHP
foreach ($mUser->selectedOffer($modelid) as $key) {
echo $key['offerId'][0];
}
also when i remove the [0] it prints both rows.
My question is how to print the first or second or which row i want?
To get specific/ first row,s column
$data = $mUser->selectedOffer($modelid);
echo $data[0]["offerId"];
And all rows column
foreach ($data as $key) {
echo $key['offerId'];
}
Use implode and array_column to echo a complete array column in one line of code:
echo implode("", array_column($yourarray, "offerId"));
The first argument of the implode is what should join the items in the array.
Your and the accepted answer has nothing that is why it's "", but it can be replaced with say: "<br>\n" if you want new line between each item of the array.

Fetch data from mysql using associative array and implode (codeigniter + MySql)

I've gathered data from multiple MySql tables and stored them as associative arrays using a foreach loop with the query.
I would like to use those associative arrays and the implode method in the mysql query to gather more data from a separate table.
I know that with the implode method, when dealing with Indexed arrays, you can just insert the array directly in the "implode section". But with associative arrays, I am unsure how to call all the available arrays and insert them in the query.
Please refer to the attached image for a detailed illustration explaining it further.
Below is also a portion of my code
public function user_implode()
{
$s_id = array(
"id" => 383
);
$count = 0;
foreach ($query->result() as $row)
{
$count = $count + 1;
$loop_number[$count] = $row->id;
}
$this->db->from('occupation');
$this->db->where_in('id',implode("','",$loop_number[$count]));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->id;
}
echo 'Total Results: ' . $query->num_rows();
}
THANKS ALOT
The second parameter to where_in() should be an array.
You are generating a string with implode() and only of the last value of the array instead of the whole array.
So all you need is:
$this->db->where_in('id', $loop_number);
And I don't see where $query comes from, it seems to be undefined when you use it in the first loop in your method.
Apart from that you should initialize your variable, $loop_number = []; before the loop.

Return only unique values from foreach

I'm currently trying to use a foreach to return all the addresses using the relation from my event model. All is fine, returns all the addresses but will return even the duplicate results. I tried the array_unique but not sure I have the syntax correct.
<?php
foreach ($data->events as $address) {
//array_unique($address, SORT_REGULAR);
echo $address->getAddressString() ."<br/> <br/>";
}
?>
You should try with array store technique using array_unique
// First Store data in $arr
$arr = array();
foreach ($data->events as $address) {
$arr[] = $address->getAddressString();
}
$unique_data = array_unique($arr);
// now use foreach loop on unique data
foreach($unique_data as $val) {
echo $val;;
}
You can add each unique element to a new array and then see if they exist with in_array():
$uniques = [];
foreach($data->events as $address){
if(!in_array($address->getAddressString(), $uniques)){
$uniques[] = $address->getAddressString();
echo $address->getAddressString()."<br><br>";
}
}
There's a faster way, if you'd like to prematurely optimize.
<?php
$arr = array();
foreach ($data->events as $address) {
$arr[$address->getAddressString()] = 'a'; // value doesn't matter
// using inherent uniqueness of keys.
}
// $addrs = array_keys($arr);
// optionally, take all those array keys and put them in values.
// keys would become regular numeric keys
?>
That should run faster than any of the other answers here. But it will only make a difference if you are dealing with large amounts of data.
If you want to echo, you will want to do array_keys if you didn't above. Here it is in one line:
echo implode(', ',array_keys($arr)); // comma separated list of unique values
Or this, for sorted:
$addrs = array_keys($arr);
sort($addrs);
echo implode(', ',$addrs); // sorted list
Finally, I'd like to add that you should be getting unique, ordered results from your data model in the first place. The database is much faster and better at simple tasks like ordering unique results than your PHP code ever will be.
SELECT DISTINCT `address` FROM `table`
WHERE `city` LIKE 'Lodi'
ORDER BY 'address' ASC
array_unique should do it. Try this:
<?php
foreach (array_unique($data->events) as $address) {
echo $address->getAddressString() ."<br/> <br/>";
}
?>
You can try this -
<?php
$all_addresses= array();
foreach ($data->events as $address) {
$all_addresses[]= $address->getAddressString();
}
$all_addresses= array_unique($all_addresses);
foreach($all_addresses as $val) {
echo $val . "<br/> <br/>";
}
?>
Or
Instead of
foreach($all_addresses as $val) {
echo $val . "<br/> <br/>";
}
Do
echo implode('<br/> <br/>', $all_addresses);
Even though the question was different I agree with Steve. You should adjust your query. Its faster, more readable and maintainable. You don't want to do anything you don't need to do.
If i gathered correctly you have to tables that are in relation. Great. Try something like this:
$var1 = YourModel::model()
->with('address_table')
->findAllByAttributes(array(-optional if you want certain columns-),
array('condition'=>'`type` LIKE :type AND `typeId` = :typeId AND `suggestionId` IS NULL', 'params'=>array(':type'=>$_GET['type'], ':typeId'=>$_GET['typeId']), 'group'=>'address_table.`column`'));
Most important thing here for you is the 'group' command which like the name says groups results and returns only unique ones. Be sure to prefix it correctly, either table name or alias depending on what you are working with.
Hope it helps.

PHP: foreach loop with array_merge to create json objects

I'm new to php but i really like like it so far!
Now i stumbled over a problem with array_merge.
This is my code, it simply grabs each table specified in my database then makes it to a big json file.:
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
foreach ($tables as $table) {
// Get tables from database
$sth = $db->query("SELECT * FROM $table");
$result = $sth->fetchAll();
// Merge arrays together
if ($arr === null) {
//echo "its 0 <br/> ";
$arr = array( "$table" => $result );
} else {
//echo "more than 0 <br/> ";
$arr2 = array( "$table" => $result );
$merge = array_merge($arr, $arr2);
}
} //End loop
echo $merge;
So far It's working somehow, I manage to get the first table "buildings" and the last table "weapons" to be displayed the way i want perfectly!
But I don't understand why it jumps over the other ones..
I believe it has something to do with $arr2 and that i need to specify a unique array for each of the tables. But how can i achieve this? Is this the way to go or is there a more efficient way to achieve this?
Thanks!
Its failing because of this line
$merge = array_merge($arr, $arr2);
Your merge is always a merge of $arr (which is the first entry in $tables) and $arr2, which is the latest entry being processed. You are not merging the data with the previously merged data, such as
$arr = array_merge($arr, $arr2)
Also, you can get rid of the if/else logic by just starting off by setting $arr to an empty array to start.
$arr = array();
You can put everything inside an unique array, like:
$myArray["$table"] = $result;
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
$tableArr = array();
foreach ($tables as $table) {
// Get tables from database
$sth = $db->query("SELECT * FROM $table");
$result = $sth->fetchAll();
if(isset($result)){
$tableArr[$table] = $result;
}else{
$tableArr[$table] = '';
}
} //End loop
print_r($tableArr);
Created new array and set index as table name and store its result in that array.
If I understand correctly...
Instead of this two lines
$arr2 = array( "$table" => $result );
$merge = array_merge($arr, $arr2);
You can try this:
$tables[$table] = $result;
Your code can be greatly simplified.
$tables = array("buildings", "medical", "other", "tools", "traps", "weapons");
foreach ($tables as & $table) {
$table = $db->query("SELECT * FROM $table")->fetchAll();
}
echo json_encode($tables);
Of course, you still need to check for errors (database and JSON errors), in order for the code to be robust, but the simpler you can make something the better. Simple is good, especially when it comes to programming.

Categories