why is php combining array when I do foreach. see below
If I enter the following code, I will get id1 id2 individually.
foreach($array as $value){
$id = $value->id;
echo $id;
}
now if I try to use the ids to do a query
foreach($array as $value){
$id = $value->id;
$result = $this->model->run_some_query($id);
var_dump($result);
}
for the above code. Since I am foreach looping not passing in an array of ids, I expect to get 2 sets of seperate array. array1 with result from id1, array2 with result from id2. but instead I get 1 array with result from both id merged together.
How to make it so the array is seperated.
You can get 2d array by doing that:
$result[id] = $this->model->run_some_query($id);
Is $this->model->run_some_query($id) returning an array reference, maybe? http://php.net/manual/en/language.references.php
you can try this code on your loop statement
foreach($array as $value){
$id = $value->id;
$result[] = $this->model->run_some_query($id);
}
var_dump($result);
Related
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.
image
Hello, as you see, indexes for both arrays is 0, how can I call "text 1" and "text 2" independently ?
Thank you.
Code is
$command2 = $db->prepare("SELECT text from khma where id IN (97,98)");
$command2->execute();
$result2 = $command2->fetchAll();
foreach ($result2 as $key ) {
print_r($key);
}
Your fetchAll will return result-set as an associative array and numeric array. You can just ignore the numeric array value. If you need to get only associate array you need to pass PDO::FETCH_ASSOC in fetch
$result = $command2->fetch(PDO::FETCH_ASSOC);
foreach ($result as $key=>$value) {
print $value['text'];
}
Figured it out. $result2[0]['text'] does the job without any foreacheas
Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}
FROM array with no key:
$array = array('apple','bee','carrot','dragon','elephant')
To
$newarray = ($apple,$bee,$carrot,$dragon,$elephant)
Why:
I want to create flexible function to get fields from a mysql db, like this:
<?php
$query = "SELECT ".$array." FROM table";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
extract($row);
echo $newarray;
}
?>
So I could:
SELECT apple, bee, carrot and echo $apple, $bee and $carrot
SELECT bee, carrot, elephant and echo $bee, $carrot, and $elephant
or whatever.
Why don't you just fetch an associative array from the database and then use the key in the associative array like this:
// assume field names are 'apple', 'bee', 'carrot', etc.
while($row = mysql_fetch_assoc($result)){
foreach($row as $key => $value) {
// this will set variables as $apple, $bee, $carrot, etc.
$$key = $value;
}
}
Of course this is not all that practical if you get more than one row in your result set, as the variables would just get overwritten.
The key to what you are wanting to do is the use of the variable variable ($$key in this case)
Oh yeah, you should also not be using mysql_* functions but rather mysqli_* or PDO.
foreach($array as $value){
$newarray[] = ${$value};
//Edited: maybe you'll need to reset the array after use it
unset($newarray);
}
Got it!
Thanks all!
foreach($sql_result['record2'] as $key ){
echo $key['ENO'];
}
when iam doing foreach loop for the above statement .It outputs (10,9,2,8,4).I need it to sort to (2,4,8,9,10)
one more thing is "$key" is of Type Array.when i do like this array_multisort($key['ENO']). how do i acheive this
$vals = array();
foreach($sql_result['record2'] as $key ){
$vals[] = $key['ENO']
}
sort($vals);
or if you want to pre-sort the values you could use usort()
Untested Code, but something like the following should work....
$tmpArray = array();
foreach ($sql_result['record2'] as $key => $value) {
array_push($tmpArray, $value['ENO']);
}
array_multisort($tmpArray, SORT_DESC);
At this point, $tmpArray will be your sorted array of values. OR, you can just do an ORDER BY clause in your SQL, in which case the result set will be ordered by the values you want.
You don't need to sort the array, you can simply append an "ORDER by ENO" to your SQL query to return an ordered result.