I've an array
Array (
[0] => value1
[1] => value2
[2] => value3
[(n)] => .....)
I want this as following:
$string1 = 'value1';
$string2 = 'value2';
$string3 = 'value3';
$string(n) = '....';
Please suggest the right way to get this.
You can use PHP extract() function.
extract($var_array, EXTR_PREFIX_ALL, "string");
Demo
Does this work for what you need?
foreach($array as $key => $row) {
$var = "string" . $key;
$$var = $row;
}
But you said you need to do a query with the values. Maybe something like this?
$sql = "SELECT * FROM mytable WHERE 1 = 1";
foreach($array as $key => $row) {
$sql .= " AND string" . $key . " = '" . $row . "'";
}
Related
Is it possible to iterate using foreach loop with key=>value but assign different variable to each lines output. I am looking for something like this:
foreach($counts as $key => $value){
$c = $key . ' => ' . $value;
$d = $key . ' => ' . $value;
};
when the sample output from vardump($counts) looks like:
array(3) { ["Type_1"]=> int(1) ["Type_2"]=> int(3) ["Type_3"]=> int(1) }
Each
int() is a quantity so ideally I would like the output to look like
$c = 1
$d = 3
$e = 1
also ok with
$c = Type_1 1
$d = Type_2 3
$e = Type_3 1
Either way, I want to access the quantities by reference the variable directly.
Your best bet is to use an array, that's what they are for:
foreach($counts as $key => $value){
$output[] = $key . ' => ' . $value;
};
It depends on why you are doing this, how you will use it and what you know, but why not use the key:
foreach($counts as $key => $value){
$output[$key] = $key . ' => ' . $value;
};
You could create an array of variable names and shift one off each time and use that, however you will never know how many there are and this is very bad practice:
$vars = range('a', 'z');
foreach($counts as $key => $value){
${array_shift($vars)} = $key . ' => ' . $value;
};
In your example you would have $a, $b and $c.
Not sure what your purpose here but you can assign different variable to each lines output by using reference variable that stores the value of the $variable inside it, that is $key in your code like below. It will help in case you know what keys will be in counts array all the time.
$counts = [ "Type_1" => 1,"Type_2"=>3, "Type_3"=> 1 ];
foreach($counts as $key => $value){
$$key = $key . ' => ' . $value;
};
echo $Type_1;
echo $Type_2;
echo $Type_3;
Output will be
Type_1 => 1
Type_2 => 3
Type_3 => 1
I need an out put like this.Can you please help me to sort this out?
a-1,2,4
b-3
for the following code:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
for($i=0;$i<count($paynum);$i++){
$paytypes = $paytype[$i];
$paynum = $payno[$i];
}
?>
Please Help
Just use array_unique, array_map and array_keys like this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$uniqArr = array_unique($paytype); //Get all the unique value from array
foreach ($uniqArr as $value) {
echo $value . "-" . implode(",",array_map("matchVal",array_keys($paytype,$value)))."<br/>";
}
function matchVal($x) {
global $payno;
return $payno[$x];
}
Output:
a-1,2,4
b-3
Demo
You can try this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$newArr = array();
for($i=0;$i<count($paytype);$i++){
if(!isset($newArr[$paytype[$i]])) {
$newArr[$paytype[$i]] = $payno[$i];
} else {
$newArr[$paytype[$i]] = $newArr[$paytype[$i]].",".$payno[$i];
}
}
print '<pre>';print_r($newArr);
?>
Output:
Array
(
[a] => 1,2,4
[b] => 3
)
Another alternative:-
Just use a simple foreach loop:-
$paytype = ['a','a','b','a'];
$payno= [1,2,3,4];
$res = [];
foreach($paytype as $k=>$v){
$res[$v] = empty($res[$v]) ? $payno[$k] : $res[$v].','.$payno[$k];
}
print '<pre>';print_r($res);
output:-
Array
(
[a] => 1,2,4
[b] => 3
)
If you want output
a-1,2,4
b-3
then add one additional foreach at the end.
foreach($res as $k=>$v){
echo "$k-$v<br>";
}
just use this code.
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$result = array();
for($i=0;$i<count($paytype);$i++){
$result[$paytype[$i]][] = $payno[$i];
}
$var = '';
foreach($result as $k => $v)
{
$var .= "{$k} - ". implode(",", $v) . "<br />";
}
print_r($var);
Result :
a - 1,2,4
b - 3
I have an array that looks something like this:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). So for example:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract():
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php
Well.. you could do something like this?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0, $something1, etc holding a value of the array assigned in the foreach.
If you want the keys to be involved you can also do this:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable.
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? Arrays are meant to be accessed by keys, so you can just do:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is:
$something1 = $the_array[2];
$something2 = $the_array[4];
How to get each result from the below line using php?
ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000
I tried with explode and foreach but without success. Thanks!
Try following:
$str = "ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000";
$final_array = array();
$data_array = explode(';', $str);
foreach($data_array as $single_data)
{
$single_data = trim($single_data);
$single_unit = explode('=', $single_data);
$single_unit[0] = trim($single_unit[0]);
$single_unit[1] = trim($single_unit[1]);
$final_array[$single_unit[0]] = $single_unit[1];
}
print_r($final_array);
Here you will get array key as your variable name and array value as its value from cell.
$text = "ssrc=15012312307;themssrc=2790404163;lp=0;rxjitter=0.001079;rxcount=933;txjitter=0.000000;txcount=735;rlp=0;rtt=0.002000";
$exploded = explode(';', $text);
foreach($exploded as $data)
{
$temp = explode('=', $data);
$result .= 'Value of "' . $temp[0] . '" is: ' . $temp[1] . '<br>';
}
echo $result;
OUTPUT:
Value of "ssrc" is: 15012312307
Value of "themssrc" is: 2790404163
Value of "lp" is: 0
Value of "rxjitter" is: 0.001079
Value of "rxcount" is: 933
Value of "txjitter" is: 0.000000
Value of "txcount" is: 735
Value of "rlp" is: 0
Value of "rtt" is: 0.002000
You can edit this code inside foreach to your requirements. Eg. to array:
$result = Array();
foreach($exploded as $data)
{
$temp = explode('=', $data);
$result[$temp[0]] = $temp[1];
}
print_r($result);
OUTPUT:
Array
(
[ssrc] => 15012312307
[themssrc] => 2790404163
[lp] => 0
[rxjitter] => 0.001079
[rxcount] => 933
[txjitter] => 0.000000
[txcount] => 735
[rlp] => 0
[rtt] => 0.002000
)
I am trying to put together a function that does the following:
retrieve a JSON encoded string from a form
decode the string to a php array
loop through the generated php array to get the values for each part of the array so that I can update a MySql table
Here is my function code so far:
public function saveTestimonials() {
$existing_testimonials_update = $this->post('data');
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
$db = Loader::db();
$sql = "UPDATE testimonials SET name=var, content=var WHERE id=var";
$db->query($sql);
$this->redirect('/dashboard/testimonials/');
}
Here is the array stored in the $update_array variable:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Mr. John Doe, Manager, ABC Ltd
[content] => my content 1.
)
[1] => stdClass Object
(
[id] => 2
[name] => Mr. Joe Smith, Manager, ABC Industries
[content] => my content 2.
)
[2] => stdClass Object
(
[id] => 3
[name] => Mr. Mike Smith, Manager, ABC Industries
[content] => my content 3.
)
[3] => stdClass Object
(
[id] => 4
[name] => Ms. Jane Doe, Manager, ABCD Ltd
[content] => my content 4.
)
)
I have got steps 1 and 2 working fine, however I am stuck on step 3.
I still learning PHP and struggle with syntax at times.
I have tried to work this one out on my own and have spent several hours on it, but just can't seem to figure this one out.
Any assistance is very much appreciated.
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
I'm using something like this. Might be a help to you!
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) );
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value);
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id'].'&'.$table);
} else { echo "Done!"; }
}
These are objects you're dealing with inside of the update_array, so you should be able to access them like this:
$update_array = json_decode($existing_testimonials_update);
foreach ($update_array as $key => $testimonials) {
$testimonials = (array) $testimonials;
foreach($testimonials as $key => $value) {
//echo "$key = $value\n";
}
}
Or, more simply, you can use the arrow operator ($testimonials->name) to access the variables.
You are getting an object from json_decode(). If you pass true as second argument to json_decode() you get an associative array.
http://php.net/manual/de/function.json-decode.php
try something like this
$db = Loader::db();
foreach ($update_array as $key => $testimonials) {
foreach($testimonials as $testimonial) {
// escape data to avoid sql injection
$id = mysql_escape_string($testimonial->id);
$name = mysql_escape_string($testimonial->name);
$content = mysql_escape_string($testimonial->content);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id='$id'";
$db->query($sql);
// TODO check for database error here
}
}
function update($table_name, $myarray, $my_wheres) {
$sql = "Update`".$table_name.
"` SET ";
$i = 0;
foreach($myarray as $key => $value) {
$sql.= $key." = '".$value."'";
if ($i < count($myarray) - 1) {
$sql.= " , ";
}
$i++;
}
if (count($my_wheres) > 0) {
$sql.= " WHERE ";
$i = 0;
foreach($my_wheres as $key => $value) {
$sql.= $key.
" = ".$value;
if ($i < count($my_wheres) - 1) {
$sql.= " AND ";
}
$i++;
}
}
return mysqli_query($sql);
}
Hope, this code can help you. Not try one by one update i think. Think performance.