Codeigniter - how to passing foreach value to inside of array - php

I use CodeIgniter 3 and libraries of http://biostall.com/codeigniter-google-maps-v3-api-library/ .
When I take the data from the database and put it into the polygon points, I encountered some error .
Severity: Warning Message: trim() expects parameter 1 to be string,
array given Filename: libraries/Googlemaps.php
Line Number: 2179
my controller function :
public function testing()
{
$config['center'] = '-8.1768084, 113.6559507';
$config['zoom'] = 'auto';
$this->googlemaps->initialize($config);
$kecamatan = $this->Peta_model->get_kecamatan();
foreach ($kecamatan as $k) {
$kcmt = $k->name;
$coor = $this->Peta_model->get_coor_by_kcmt($kcmt);
if ($coor) {
$polygon = array(
'points' => array() ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
foreach ($coor as $c) {
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
}
$this->googlemaps->add_polygon($polygon);
}
}
$user = $this->ion_auth->user()->row();
$user_level = $this->ion_auth->get_users_groups($user->id)->row();
$data = array(
'user' => $user ,
'user_level' => $user_level ,
'title' => 'Peta' ,
'content' => 'peta/v_peta' ,
'map' => $this->googlemaps->create_map(),
);
$this->load->view('dashboard/layout', $data);
}
normaly add polygon is :
$polygon = array(
'points' => array('37.425, -122.1321',
'37.4422, -122.1622',
'37.4412, -122.1322',
'37.425, -122.1021') ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
$this->googlemaps->add_polygon($polygon);
how do I fix it ?

You are storing an array in $polygon ['points'][].
i think you should store a string. like..
$polygon ['points'][] = "'".$c->latitude.",".$c->longitude."'";

Solved !. only cahange
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
to
$polygon ['points'][] = $c->latitude.','.$c->longitude;
thank you #Muhammad Suhaib

Related

Use variable to query MongoDB with PHP

I need to dynamically build a complex MongoDB query before executing it in PHP. My query line looks like $cursor = $c_sbc->aggregate($query_string);, where $query_string is something like [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]].
Copy-and-pasting the above-given example to replace $query_string gives the desired result. However, running it with $query_string in place gives an error saying it expects an array, not a string. How do I get this query to work?
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163
Edit: relevant PHP
$query = $_POST['screen'];
$t = array(
"revenue" => 1000,
"costofgoodssold" => 1001
);
$data_array = [];
//turn words into data.XXXX codes
function translate($match){
global $t;
global $data_array;
foreach($match as $m){
$d = "data.".$t[$m];
$data_array[] = $d;
return $d;
}
}
$query = preg_replace('/\s/', '', $query); //strip whitespace
$query = strtolower($query);
$query = preg_replace_callback('/([A-Z]+)/i','translate', $query);
echo "<br>Query: ";
print_r($query);
echo "<br>";
$client = new MongoDB\Client("mongodb://localhost:27017");
$db = $client->gc_dev;
$c_sbc = $db->screenByCompany;
$for_years = [-1]; //default is TTM
$symbols = ['goog', 'fb', 'crmt', 'vlgea', 'ko', 'pep', 'flws'];
for($i=0;$i<count($symbols);$i++){
$sym = $symbols[$i];
for($j=0;$j<count($for_years);$j++){
$k = $for_years[$j];
//build query for data
$data_query = "";
foreach($data_array as $d){
if($data_query == ""){ //first go-around, no need for comma
$data_query .= "['first' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}else{
//$data_query .= ",['second' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
}
echo "<br>\$query_string: ".$query_string;
$cursor = $c_sbc->aggregate($query_string);
//$cursor = $c_sbc->aggregate([['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000',-1]]]]]);
$cursor = iterator_to_array($cursor);
//var_dump($cursor);
echo "Cursor: ".$cursor[0]['first'] . "<br><br>";
}
Results in:
Query: (data.1000-data.1001)>1,000
$query_string: [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]]
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163
Found your error. You are declaring $query_string as a string and not as an array like what the function aggregate is asking for. Your code is:
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
Replace it with:
$query_string = [['\$match' => ['symbol' => \$sym]],['\$project' => $data_query]];

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

Removing a deeply nested object property using an array of object property names

Original Title: How can I dynamically enclose attributes in variable before actual object call
Generic Question
How can I create $target in a way that it can be correctly var_dumped?
$type = 'lib';
$target = 'test->test2';
var_dump($GLOBALS[$this->context]->$type->test->test2);//returns object(test\test2)#15 (0) { }
var_dump($GLOBALS[$this->context]->$type->{$target}); //returns NULL ( Undefined property: stdClass::$test->test2 )
More Examples
this (below) works like a charm
$target = 'test';
$type = new \stdClass();
$type->test = new \stdClass();
$type->test->test2 = 5;
var_dump($type->$target); // Returns object(stdClass)#24 (1) { ["test2"]=> int(5) }
this (below) does not :
$target = 'test->test2';
$type = new \stdClass();
$type->test = new \stdClass();
$type->test->test2 = 5;
var_dump($type->$target);// Returns NULL (Notice: Undefined property: stdClass::$test->test2)
Real Case :
I want to unset $GLOBALS[$this->context]->$type->test->test2
My first though :
public function unSys($type, $thing) {
//$type = 'lib';
//$thing = 'test/test2';
$parts = explode('/',$thing);
$final = implode('->',$parts);
unset($GLOBALS[$this->context]->$type->{$final});
}
What I've tried after that :
...
$parts = explode('/',$thing);
$target = $GLOBALS[$this->context]->$type;
foreach ($parts as $value) {
$target = $target->$value;
}
unset($target);
var_dump($GLOBALS[$this->context]->$type->test->test2);//still exist
...
I also tried passing by reference without luck :
...
$target = &$GLOBALS[$this->context]->$type;
...
Guillaume,
I think you're wanting to use an array of property names that represent a chain of nested objects to remove the last nested object property.
See if this code makes sense and solves your problem.
<?PHP
$GLOBALS['tmp'] = (object)array( 'lib' => (object)array( 'test' => (object)array( 'test2' => (object)array()) ) );
var_dump( $GLOBALS['tmp'] );
$context = 'tmp';
$type = 'lib';
$thing = 'test/test2';
$parts = explode('/',$thing);
$target = $GLOBALS[$context]->$type;
var_dump( $target );
var_dump( $parts );
$itemToUnset = array_pop( $parts );
foreach ($parts as &$value) {
$target =& $target->$value;
}
unset( $target->{$itemToUnset} );
var_dump( $GLOBALS['tmp'] );
// test 2 is not set
var_dump( $GLOBALS['tmp']->lib->test->test2 );
The output looks like this:
object(stdClass)[4]
public 'lib' =>
object(stdClass)[3]
public 'test' =>
object(stdClass)[2]
public 'test2' =>
object(stdClass)[1]
...
object(stdClass)[3]
public 'test' =>
object(stdClass)[2]
public 'test2' =>
object(stdClass)[1]
array (size=2)
0 => string 'test' (length=4)
1 => string 'test2' (length=5)
object(stdClass)[4]
public 'lib' =>
object(stdClass)[3]
public 'test' => &
object(stdClass)[2]
Notice: Undefined property: stdClass::$test2

Add $_POST to array

I have 1 array:
$meta_array = array(
'lot',
'floor',
'block'
);
How can I convert the above array to show
'lot' => $_POST['lot'], 'floor' => $_POST['floor']
so I can update_post_meta($new, 'number' , $meta_array) like this.
I am trying to save some KBs as my form php size is getting rather large.
Thank you for your advice.
FINALLY - I DID THIS
$new_meta = array();
foreach($meta_array as $val){
if (isset($_POST[$val])) {
$new_meta[$val] = sanitize_array_text_field($_POST[$val]);
}
}
update_post_meta($new, 'property', $new_meta);
use :
$posted = array_combine ($meta_array, $_POST);
You will get :
Array(
[lot] => $_POST['lot'],
[floor] => $_POST['floor'],
[block] => $_POST['block']
)
Use a foreach loop:
$meta_array = array('lot', 'floor', 'block');
$another_array = array();
foreach($meta_array as $val){
$another_array[$val] = $_POST[$val];
}
You could also do:
if(isset($_POST['lot']))
$meta_array['lot'] = $_POST['lot'];
if(isset($_POST['floor']))
$meta_array['floor'] = $_POST['floor'];
if(isset($_POST['block']))
$meta_array['block'] = $_POST['block'];
Using isset() is a little safer.

Cakephp set function not passing variables from controller to the view

I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning

Categories