How can i get Array values to separate php variables - php

I am trying to retrieve records in MySQL DB.I want to retrieve all the records belong to the img_path column.from the following code I am getting results as an array.but iw ant them as separate variables.
My code
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = array(
'img_path' => $row['img_path'],
);
}
print_r($productitems);
Current Output
Array (
[0] => Array ( [img_path] => img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png )
[1] => Array ( [img_path] => img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg )
[2] => Array ( [img_path] => img ) )
expected output
$variable1 = img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png;
$variable2 = img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg;

You can use extract function like this:
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $row) {
$productitems[] = $row['img_path'];
}
extract($productitems, EXTR_PREFIX_ALL, "variable");
echo $variable_0;
echo $variable_1;
echo $variable_2;

You can do that :
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $k => $row) {
$varName = 'var' . $k;
$$varName = array(
'img_path' => $row['img_path'],
);
}
And you will have access to $var0, $var1, and so forth.

You might use, extract() function. Docs here
The extract() function imports variables into the local symbol table
from an array.
This function uses array keys as variable names and values as variable
values. For each element it will create a variable in the current
symbol table.
This function returns the number of variables extracted on success.

Use list().
http://php.net/manual/en/function.list.php
From the manual:
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

You can also use the following code, where you do not need to use an additional function like list() or extract(). It is also a very minimalistic approach.
$result_list = array();
while($row = mysqli_fetch_array($query)) {
$result_list[] = $row;
}
foreach($result_list as $key => $row) {
${'img_path_'.$key} = $row['img_path'];
}
/*
Output:
["img_path_0"]=>
string(50) "img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png"
["img_path_1"]=>
string(50) "img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg"
["img_path_2"]=>
string(3) "img"
*/

Related

how can i use values in array ? (php)

I wanna use values in array of array like:
$result = $conn->query("SELECT performer,file_id,title,duration FROM
databasebot WHERE performer = '$message' or title = '$message'");
$poets = array(
"keyboard" => array()
);
while ($row = mysqli_fetch_row($result)) {
$poets['keyboard'][] = array($row[2],$row[1]);
}
I wanna echo $poets values of $row[1]. How can I do that?
Loop through the array in $poets['keyboard']. In each element, $poets[1] will be in the [1] sub-element.
foreach ($poets['keyboard'] as $kb) {
echo $kb[1];
}

Pushing two values from the database to one array

On line 6 I am pushing a value from the database to the array called $products. I would now like to give another value from the database ($row->image) to the same array which matches with $row->name.
Maybe it could make sense to use a two dimensional array but I don't know how to do this in this case.
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
if($result = $db->query("SELECT * FROM produkte WHERE $value = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push($products, $row->name);
}
}
}
else {
array_push($products, 'error');
}
}
The result should show me the name and the image of both values which belong together.
You could do this, assuming you already have your $row->name and $row->image matching logic sorted:
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image) );
}
You can try it like this:
$products = array();
foreach ( $_POST['selected_checkboxes'] as $value ) {
if ( $result = $db->query( "SELECT * FROM produkte WHERE $value = 1" ) ) {
while ( $row = $result->fetch_object() ) {
// if your name is unique you can do it like this,
// if not just take $row->id as index
if( isset( $products[$row->name] ) ) continue;
$products[$row->name] = array( "name" => $row->name, "image" => $row->image );
}
} else {
array_push( $products, 'error' );
}
}
// if you want to have plain digits as index you can get a reindexed array
$products = array_values( $products );
then you will get an array like that:
array(//$products
array(
"name" => "productname",
"image" => "productimage"
)
);
I think you can achieve that if you use a stdClass object.
$std = new stdClass();
$std->name = $row->name;
$std->image = $row->image;
array_push($products, $std);
Or you can change your sql query to
SELECT name, image FROM produkte WHERE $value = 1
and
array_push($products, $row);

change key names in array in php

ok..I'm trying to re-map the keynames of a key-value array in php using a fieldmap array ie.
i want the $outRow array to hold $inRow['name1'] = 10 to $outRow['name_1'] = 10 for a large set of pre-mapped values..
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
public function getListings($inSql) {
// get data from new table
$result = mysql_query($inSql);
if (!result) {
throw new exception("retsTranslate SQL Error: $inSql");
}
while ($row = mysql_fetch_assoc($result)) {
$outResult[] = $this->mapRow($row);
}
return $outResult;
} // end getListings
this is not working..I'm getting the array but its using $outResult[0][keyname]...I hope this is clear enough :)
$fieldmap=array("name1"=>"name_1","name2"=>"name_2");
private function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[$this->fieldmap[$key]][] = $value;
}
return $outRow;
} // end mapRow
while ($row = mysql_fetch_assoc($result)) {
//$outResult[] = $this->mapRow($row);
$outResult[= $this->mapRow($row);
}
I commented your line of code and added new one..it definitely got what you mentioned in question.
If you can structure your arrays to where the keys align with the values (see example below) you can use PHP array_combine(). Just know that you will need to make absolutely sure the array is ordered correctly.
<?php
$fieldmap = array( 'name_1', 'name_2', 'name_3' );
private function mapRow($inRow)
{
$outRow = array_combine( $this->fieldmap, $inRow );
return $outRow;
}
For example, if your array was:
array( 'name1' => 10, 'name2' => 20, 'name3' => 30 );
The new result would be:
array( 'name_1' => 10, 'name_2' => 20, 'name_3' => 30 );
Let me know if this helps.
Try this:
function mapRow($inRow) {
$outRow = array();
foreach($inRow as $key => $value) {
$outRow[preg_replace('/\d/', '_$0', $key,1)] = $value;
}
return $outRow;
}

PHP invalid argument in foreach loop

I have a main php file that I am including in my php file that I am calling the functions from.
My main file has this function
function GetComments()
{
global $server;
global $info;
global $dbhandle;
$query = "SELECT GbId, fname, lname, comment FROM Guestbook";
$result = sqlsrv_query($dbhandle, $query);
while($row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
{
$array[$row['GbId']] = array(
'f' => trim($row['fname']),
'l' => trim($row['lname']),
'c' => trim($row['comment']));
}
return $array;
}
and my webpage document has this code
<?php
$array = GetComments();
foreach($array as $key => $info)
{
echo $info['f']." ".$info['l']." said ".""".$info['c']."""."<br /><br />";
}
Close();
?>
This code works fine when the foreach loop is in the main file, but I get a warning after all the data is printed out when it is in the webpage file. I'm not too concerned about it as it still works, but I would like to either get rid of it, fix it, or at least know why it is happening.
Thanks
Error occurs because foreach expects array as input, but provided variable is not array at some piont.
Solution : If it is not array, make it a null array.
Try adding this line if(!is_array($array)){ $array = array(); } after $array = GetComments();
$array = GetComments();
if(!is_array($array)){ $array = array(); }
EDIT : Declare the array before while loop in your function
$array = array();
while($row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
{
$array[$row['GbId']] = array(
'f' => trim($row['fname']),
'l' => trim($row['lname']),
'c' => trim($row['comment']));
}
return $array;
you can use like this:
foreach( (array) $array as $key => $info)

Add data dynamically to an Array

I want to add data to an array dynamically. How can I do that? Example
$arr1 = [
'aaa',
'bbb',
'ccc',
];
// How can I now add another value?
$arr2 = [
'A' => 'aaa',
'B' => 'bbb',
'C' => 'ccc',
];
// How can I now add a D?
There are quite a few ways to work with dynamic arrays in PHP.
Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
Let's say you have defined an empty array:
$myArr = array();
If you want to simply add an element, e.g. 'New Element to Array', write
$myArr[] = 'New Element to Array';
if you are calling the data from the database, below code will work fine
$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
while($result = mysql_fetch_object($query))
{
//adding data to the array
$myArr[] = $result->$element;
}
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
Like this?:
$array[] = 'newItem';
In additon to directly accessing the array, there is also
array_push — Push one or more elements onto the end of array
$dynamicarray = array();
for($i=0;$i<10;$i++)
{
$dynamicarray[$i]=$i;
}
Adding array elements dynamically to an Array And adding new element
to an Array
$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
$arr['feeds'][$count]['feed_id'] = $row->feed_id;
$arr['feeds'][$count]['feed_title'] = $row->feed_title;
$arr['feeds'][$count]['feed_url'] = $row->feed_url;
$arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
foreach ($newelt as $cat) {
array_push($samplearr, $cat);
}
++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING
$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);
just for fun...
$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');
$array_c = array_merge($array_a,$array_b);
$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}
print_r($array_d);
print_r($array_e);
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}

Categories