I have a question here on how to parse a $POST_['value'] (e.g 3785,3789,3790,3787 ) from a form to an array($POST_['value']) and do foreach. Please see the sample code below:
function someFunction(){
$html = '';
$int = $_POST['Ids']; //POST the value as 3785,3789,3790,3787
$IDs = array($int);
foreach ($IDs as $ID) {
$intVal = '<int>' . $ID .'</int>';
$html .= $intVal;
}
return $html;
}
however the result displays it as the ****whole string** rather than array**.
And if I put the array(3785,3789,3790,3787) like this, it will parse as array in foreach. How to convert the $POST_['IDs'] to number or some sort in order to be recognised as array?
Thanks
Mike
This will work
function someFunction(){
$html = '';
$int = $_POST['Ids']; //POST the value as 3785,3789,3790,3787
$IDs = explode(',', $_POST['Ids']);
foreach ($IDs as $ID) {
$intVal = '<int>' . $ID .'</int>';
$html .= $intVal;
}
return $html;
}
You need to do a quick fix to the following line:
<?php
$IDs = explode(",", $int);
Related
I am trying to implode the for each loop to get results like this
["86","87","88"]
Code I am using to achieve results as follows
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tag_data = $data->tag_id;
array_push($tags, $tag_data );
}
Use json_encode() to output that format:
echo json_encode($tags);
implode will change your data to a string.
$arr = ['1', '2', '3'];
$imp = implode(', ', $arr);
echo $imp; // output: 1, 2, 3
Probably, what you want is -
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tags[] = $data->tag_id;
}
Hope it helps you. :)
I am experimenting with PHPQuery (https://code.google.com/p/phpquery/) to scrape data from my website.
I want to extract meta information from a page.
Here is what I have tried so far :
$html = phpQuery::newDocumentHTML($file, $charset = 'utf-8');
$MetaItems = [];
foreach (pq('meta') as $keys) {
$names = trim(strtolower(pq($keys)->attr('name')));
if ($names !== null && $names !== '') {
array_push($MetaItems, $names);
}
}
for ($i=0; $i < count($MetaItems); $i++) {
$test = 'meta[name="' . $MetaItems[$i] . '"]';
echo pq($test)->html();
}
Above :
In $MetaItems I get all the meta attribute name.This array is filled correctly.
But selecting and extracting text is not working. How do i get the above code to work?
Thanks.
You want an assoc array with name => content, correct? Try this:
$metaItems = array();
foreach(pq('meta') as $meta) {
$key = pq($meta)->attr('name');
$value = pq($meta)->attr('content');
$metaItems[$key] = $value;
}
var_dump($metaItems);
Going under the assumption that the values you are extracting are exactly the same as the values of the name attributes your trying to get... I'm pretty sure the value of the name attribute is case sensitive. You need to remove the strtolower and the trim. Both could be causing issues. I would replace the first part with this:
$html = phpQuery::newDocumentHTML($file, $charset = 'utf-8');
$MetaItems = [];
foreach (pq('meta') as $keys) {
$names = pq($keys)->attr('name');
if (!empty($names) && trim($names)) {
array_push($MetaItems, $names);
}
}
hope that helps
I have the following function which works fine.
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$result[$object->id] = $object->first_name . ' ' . $object->last_name;
}
return $result;
}
However, I would like to pass in an array to $items, and have that exploded, so that I dont have to specify first_name and last_name manually.
If $item was only a single value (and not an array), then it would be simple:
$result[$object->id] = $object->$item;
But I have no idea how to make this work if $items contains multiple values and I want to join them with a space. Something like, the following, but I need to get the $object in there
$items = array('first_name', 'last_name');
$result[$object->id] = implode(' ', $items);
Do I get you right that you`d like to use the strings in $item as property-names of $object?
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$valuesToAssign = array();
foreach ($items as $property) {
$valuesToAssign[] = $object->$property;
}
$result[$object->id] = implode(' ', $valuesToAssign);
}
return $result;
}
I have no idea to avoid the second foreach, but that gives you the desired result.
Not sure if I got you right, but how about this:
function foo($objects, $items = array()) {
$result = array();
$keys = array_flip($items);
foreach ($objects as $object) {
// Cast object to array, then omit all the stuff that is not in $items
$values = array_intersect_key((array) $object, $keys);
// Glue the pieces together
$result[$object->id] = implode(' ', $values);
}
return $result;
}
Demo: http://codepad.viper-7.com/l8vmGr
This is my $data variable:
cv = 1,2,3,4,5:::cpt = 4,5 ...
Now I need some function, where I can add the number as param (number will be $data number value).
for example.
function getPermission($id) {
... return $something;
}
Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.
So, to be clear:
if I call the function like this:
echo getPermission(4); output will be "cv" and "cpt".
but if I call it this way:
echo getPermission(1);
it'll only output "cv" because number (1) is located in the cv key.
Hope you guys understand, feel free to ask if something aren't clear enough.
$str = 'cv = 1,2,3,4,5:::cpt = 4,5';
$tmp = explode(':::', $str);
$data = array();
foreach ($tmp as $arr) {
$tokens = explode(' = ', $arr);
$data[$tokens[0]] = explode(',', $tokens[1]);
}
print_r(getPermission(4, $data));
print_r(getPermission(1, $data));
function getPermission($id, $data) {
$out = array();
foreach ($data as $key => $arr) {
if (in_array($id, $arr)) $out[] = $key;
}
return $out;
}
I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}