PHP: Getter and Setter while using Arrays? - php

I'm extremely new to php so excuse my code if you think it is a mess but I've been trying to figure this out for hours.
I am trying to use the getter and setter method to pull functionality from a class then use an array to create new objects based off the class. $_GET is to get the input foodNumber from a HTML form which determines which position in the array is chosen. So if 0 is inputted on the form, it represents Salad, if 2 is entered on the form it should mean Vegetables.
So in my mind, the $foodObject is creating a new object from the class FoodArray. I am trying to make the objects be in an array, so in this case $foodArray. But I don't know how to input values through an array using the getter setter method using the class functions or how to call them.
Thanks in advance!
<?php
class FoodArray {
private $foodValue;
public function setFoodValue($x){
$this->foodValue=$x;
}
public function getFoodValue(){
return $this->foodValue;
}
}
$foodNumber = $_GET['foodNumber'];
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodArray=$foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodArray[$foodNumber];
?>
/////HTML FORM/////
<html>
<body>
<form action="class_with_getter_and_setter.php" method="get">
<b>Choose a number between 0-4 and get a mystery food!</b>
<input type="text" name="foodNumber">
<input type="submit">
</form>
</body>
</html>

I'm not exactly sure what your final intention is but I can try to point out a couple of places where you are going wrong:
The setFoodValue() method of the FoodArray object is never called so $foodValue has no value
$foodArray is set as an array but is immediately overwritten when you call the line $foodObject->getFoodValue()
$foodObject->getFoodValue() actually returns nothing because $foodValue was never set
There should be no difference in your getters and setters if you are passing an array or a string you could pass them and retrieve them the same way.
Again not sure exactly what you are trying to accomplish but you could try something like this:
$foodObject = new FoodArray;
$foodArray = array ("Salad", "Vegetables", "Pasta", "Pizza", "Burgers");
$foodObject->setFoodValue($foodArray);
$foodObjectArray = $foodObject->getFoodValue();
echo "The number you chose is ". $foodNumber;
echo "The food item you choose is".$foodObjectArray[$foodNumber];

If the problem is that echo "The food item you choose is".$foodArray[$foodnumber]; doesn't produce what you expect, there are two potential problems:
I'm not clear on the intent of your $foodObject. However, the $foodArray=$foodObject->getFoodValue(); may be messing it up, unless the internal $foodValue property is (like) the $foodArray you declare with Salad, Vegetables, etc.
When echo-ing $foodArray[$foodnumber], the 'n' in number is lowercase where above you set $foodNumber (capital 'N')

Related

Can't Delete Specific Keys and Values from JSON in PHP

I'm trying to delete specific key and value pair from external JSON file in PHP when user clicked delete button on the page.
I'm not familiar with PHP so I couldn't able to figure out what I'm doing wrong. I looked at more than 20 questions on stackoverflow but none of them helped to solve my problem.
What I'm trying to achieve in general to write a simple script which user can write something in textbox and submit, show it on the page and when user wants delete it. (I have done the submit and showing part but stuck on deleting part)
Firstly my JSON file:
{
"departman1":
[
{"departman1stage":"John"},
{"departman1stage":"Test"},
{"departman1stage":"Test2"}
]
}
Part of my index.php file:
...
include ('yazdir.php');
include ('sil.php');
<div class='icerik'>
<?php
foreach ($json['departman1'] AS $d){
echo '<p class="' . $d['departman1stage'] .'">';
echo "--> ";
echo $d['departman1stage'];
echo '<form action="sil.php" method="POST"><button type="submit" class="dugme" name="' . $d['departman1stage'] .'"><i class="fa fa-trash"></i></button></form>';
echo "<br>";
echo "</p>";
}
?>
</div>
<br>
<form action="yazdir.php" method="POST">
<div class="icerik"><p><input type="text" name="departman1stage"></p></div>
<br>
<input type="submit" value="Gonder">
</form>
...
It is not related with problem but I still put my yazdir.php code:
$json_sifreli = file_get_contents ("data.json");
$json = json_decode($json_sifreli, true);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = array(
'departman1stage' => $_POST["departman1stage"]
);
array_push ( $json['departman1'], $data );
$json_sifreleme = json_encode($json, true);
file_put_contents('data.json', $json_sifreleme);
}
sil.php is currently blank, as I said I tried different methods. Some of them deleted whole JSON file and put 'null' into it. Some of them deleted unrelated key and value pair. As a last resort, I decided to write here.
Thanks in advance, sorry for taking your time.
You can delete keys using the PHP built-in unset function. It works on individual array keys:
<?php
$foo = [
'a' => 23,
'b' => 42,
];
unset($foo['a']);
var_dump($foo);
Results in:
array(1) {
["b"]=>
int(42)
}
PHP arrays are hash maps, no matter if keys are strings are numeric. In your example JSON, departman1 is an array with numeric keys. You can delete numeric keys with unset as well:
$bar = [
23,
42,
];
unset($bar[0]);
var_dump($bar);
Results in:
array(1) {
[1]=>
int(42)
}
Note that the dump shows 1 as key. Unsetting numeric keys does not cause the array to be renumbered. You end up with holes and this will show up in json_encode output:
echo json_encode($bar);
// Results in: {"1":42}
So you could go through the swamp of using a JSON file as data store, but be cautioned it's a Pandoras Box full of hardships. It also doesn't scale beyond one concurrent user because json_encode and json_decode do not provide ACID properties, which database management systems provide you. My suggestion: ditch the JSON file and pick up a proper database such as PostgreSQL or MySQL (they have good support in PHP via PDO).
view the example code in playground
(BTW: You are using the $_POST variable directly, which is unsafe user input. Sanitizing input can be done with PHP built-in filter_var function.)

Access serialized Array in php - WORDPRESS POSTMETA

I have a serialized array that I need to access:-
a:5:{s:5:"width";i:750;s:6:"height";i:330;s:4:"file";s:25:"2017/12/Sophrologie-1.jpg";s:5:"sizes";a:21:{s:20:"listingpro-blog-grid";a:4:{s:4:"file";s:25:"Sophrologie-1-372x240.jpg";s:5:"width";i:372;s:6:"height";i:240;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-blog-grid2";a:4:{s:4:"file";s:25:"Sophrologie-1-372x330.jpg";s:5:"width";i:372;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-blog-grid3";a:4:{s:4:"file";s:25:"Sophrologie-1-672x330.jpg";s:5:"width";i:672;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:23:"listingpro-listing-grid";a:4:{s:4:"file";s:25:"Sophrologie-1-272x231.jpg";s:5:"width";i:272;s:6:"height";i:231;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro-listing-gallery";a:4:{s:4:"file";s:25:"Sophrologie-1-580x330.jpg";s:5:"width";i:580;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:21:"listingpro-list-thumb";a:4:{s:4:"file";s:25:"Sophrologie-1-287x190.jpg";s:5:"width";i:287;s:6:"height";i:190;s:9:"mime-type";s:10:"image/jpeg";}s:23:"listingpro-author-thumb";a:4:{s:4:"file";s:23:"Sophrologie-1-63x63.jpg";s:5:"width";i:63;s:6:"height";i:63;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb1";a:4:{s:4:"file";s:25:"Sophrologie-1-458x330.jpg";s:5:"width";i:458;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb2";a:4:{s:4:"file";s:25:"Sophrologie-1-360x198.jpg";s:5:"width";i:360;s:6:"height";i:198;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb3";a:4:{s:4:"file";s:25:"Sophrologie-1-263x198.jpg";s:5:"width";i:263;s:6:"height";i:198;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-gallery-thumb4";a:4:{s:4:"file";s:25:"Sophrologie-1-653x199.jpg";s:5:"width";i:653;s:6:"height";i:199;s:9:"mime-type";s:10:"image/jpeg";}s:25:"listingpro-detail_gallery";a:4:{s:4:"file";s:25:"Sophrologie-1-383x330.jpg";s:5:"width";i:383;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:33:"listingpro-checkout-listing-thumb";a:4:{s:4:"file";s:24:"Sophrologie-1-220x80.jpg";s:5:"width";i:220;s:6:"height";i:80;s:9:"mime-type";s:10:"image/jpeg";}s:31:"listingpro-review-gallery-thumb";a:4:{s:4:"file";s:25:"Sophrologie-1-184x135.jpg";s:5:"width";i:184;s:6:"height";i:135;s:9:"mime-type";s:10:"image/jpeg";}s:17:"listingpro-thumb4";a:4:{s:4:"file";s:25:"Sophrologie-1-272x300.jpg";s:5:"width";i:272;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location270_400";a:4:{s:4:"file";s:25:"Sophrologie-1-270x330.jpg";s:5:"width";i:270;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location570_455";a:4:{s:4:"file";s:25:"Sophrologie-1-570x330.jpg";s:5:"width";i:570;s:6:"height";i:330;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location570_228";a:4:{s:4:"file";s:25:"Sophrologie-1-570x228.jpg";s:5:"width";i:570;s:6:"height";i:228;s:9:"mime-type";s:10:"image/jpeg";}s:26:"listingpro_location270_197";a:4:{s:4:"file";s:25:"Sophrologie-1-270x197.jpg";s:5:"width";i:270;s:6:"height";i:197;s:9:"mime-type";s:10:"image/jpeg";}s:22:"listingpro_cats270_213";a:4:{s:4:"file";s:25:"Sophrologie-1-270x213.jpg";s:5:"width";i:270;s:6:"height";i:213;s:9:"mime-type";s:10:"image/jpeg";}s:22:"Sophrologie-1-1170x400";a:5:{s:4:"file";s:25:"Sophrologie-1-1170x400jpg";s:5:"width";s:4:"1170";s:6:"height";s:3:"400";s:9:"mime-type";s:10:"image/jpeg";s:7:"nova-wp";b:1;}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:19:"Maygutyak - Fotolia";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
I want to retrieve the Sophrologie-1-1170x400jpg filename from it (at the bottom of the array).
I can't figure out how to retrieve this filename into this array. The clue is that there is a nova-wp value in that row.
This array comes fromwp-postmeta table in an wordpress installation.
If you could bring me to the direction, I'll be very thankful.
The data you show has been produced through serialization. Use the unserialize function in order to bring it back to its original state:
$data = unserialize($text);
Then, traverse the deserialized data it in order to retrieve the value you are looking for:
echo $data["sizes"]["Sophrologie-1-1170x400"]["file"];
// Output: Sophrologie-1-1170x400jpg
A working demo can be found here.
If you need to scan your data in order to find the correct value, you can use the following code:
$data = unserialize($text);
if (array_key_exists("Sophrologie-1-1170x400", $data["sizes"])) {
echo $data["sizes"]["Sophrologie-1-1170x400"]["file"];
} else {
echo "File not found!";
}

PHP Class properties being overwritten when I store to array

There is probably a very simple explanation for this, but I've had this code working for months, and now all of a sudden today it doesn't work.
I retrieve all the rows from a table. I have and object which is an entity model of the table I'm selecting from. As I read the rows from the associative result array, I'm storing each property using "$this->propertyName," and then I'm pushing each object to an array. Before I ended up with an array of objects, now I end up with an array of the same object repeated. Here's a code snippet:
$mdSelectALL_sql="SELECT * FROM member_data";
$mdSelectALL=mysql_query($mdSelectALL_sql,$mdConn);
if(!$mdSelectALL){
die('Error: ' . mysql_error());
}
else{
echo "RETURNING ALL MEMBER DATA RECORDS!!!<br>";
//store all records into array
while($row=mysql_fetch_array($mdSelectALL))
{
$this->mdId=$row['md_id'];
$this->mdFname=$row['md_fname'];
$this->mdLname=$row['md_lname'];
$this->mdEmail=$row['md_email'];
$this->mdTwitter=$row['md_twitter'];
$this->mdFacebook=$row['md_facebook'];
$this->mdMyspace=$row['md_myspace'];
$this->mdPhoneNumber=$row['md_phonenumber'];
$this->mdNotes=$row['md_notes'];
//store records in array
array_push($mdArray,$this);
}//end while
// print_r($mdArray); prints the array and each element is the last record encountered in the SQL retrieval
return $mdArray;
}//end else
My getters and setters look like this for each property:
function get_mdId(){
return $this->mdId;
}
function set_mdId($id){
$this->mdId=$id;
}
And suggestions or ideas?
-TU
Objects are passed around by reference. That means that when you change a value, that value will change everywhere that you have used that object.
As you are storing the same object every time - $this - you end up with an array of references to the same object.
To solve it, you can do:
$mdArray = array();
while($row=mysql_fetch_array($mdSelectALL))
{
$tmp_object = new MyObject; // fill in the name of your object...
$tmp_object->mdId=$row['md_id'];
...
array_push($mdArray, $tmp_object);
}

parse GeoJson String in PHP

I want to get polygon coordinates from below String.
{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}
This is GeoJson string that i decode to array with below code:
$polygon = CJSON::decode($str);
when i want to get polygon i get error!
$var= $polygon->polygon;
or with below code:
$polygon = CJSON::decode($str,true);
$var = $polygon['polygon'];
although for getting coordinates:
foreach($polygon as $key=>$value)
$coordinates = $value['coordinates'];
or
$coordinates = $value[coordinates];
how can i get coordinates from geojson that i send from javascript to php for saving on postgresql with postgis?
$polygon->polygon->geometry->coordinates[0]
or
$polygon['polygon']['geometry']['coordinates'][0]
what you have is a multidimensional array/object not sure which its being output to when decoded in your case as it appears you have a class doing it I would have just used json_decode, but anyway. Yea from the looks of it, polygon is the main object, then in it is geometry which is an object that has type and coordinates, and then coordinates has multiple objects/arrays in it.
the above samples if I typed them right will show the first set of coordinates in that object. Of course you could run it through a loop ie:
In the case that it is an object assuming your Class decodes as an object and not an array. Not exactly sure what $polygon = CJSON::decode($str,true); does. But if its anything like json_decode() then you should be all set.
This is my method of breaking down the object as you present here, its worth noting you may want to check counts, and see if the object is set first, or if the property exists in the object to prevent other means of the code breaking down the road. But what I have here is just pure example at its core, it will server its purpose though. But will not error handle which is why I say you may want to elaborate further on it doing those checks.
Anyway heres my code:
<?php
$str = '{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}';
$polygon = json_decode($str);
echo'<pre>';print_r($polygon);echo'</pre>';
$set = 1;
foreach($polygon->polygon->geometry->coordinates[0] as $coordinates)
{
echo 'Set '.$set.': ';$set++;
echo $coordinates[0].','.$coordinates[1].'<br>';
}
?>
see it in action http://7pz.net/geojson-parse.php (scroll to the bottom)
This should give you an array of all the coordinates and print them out line by line:
$string = '{"polygon":{"type":"Feature","properties":[],"geometry":{"type":"Polygon","coordinates":[[[-7302732.4720101,6527844.6333235],[-3193477.8319711,6606116.1502766],[-5111129.9973226,5001550.0527375],[-6637424.5779086,4884142.7773079],[-7772361.5737289,5158093.0866438],[-7302732.4720101,6527844.6333235]]]},"crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}}}}';
$json = json_decode($string);
$coords_array = $json->polygon->geometry->coordinates[0];
foreach($coords_array as $c_a) {
echo $c_a[0] . "," .$c_a[1] . "<br>";
}
Access with:
$coords_array[0];
$coords_array[1];
$coords_array[2];
etc.
Basically you can turn the JSON string into an object and access each element with the -> notation.
I usally use a site called http://jsonviewer.stack.hu/ to decode JSON and find the path I need, then simply write them out as they appear, as in as in the above - $json->polygon->geometry->coordinates;.
Try it out yourself on the site.

How to dynamicly set a array variable?

I have a problem with this code:
$a['i'] = 1;
$b = '$a[\'i\']';
echo $$b;
It display an error:
Notice: Undefined variable: $a['i'] in test.php on line 6
Is it possible to create dynamic array variable?
Thanks for your time.
EDIT: In my example I am trying to edit an multidimensional array. There is a problem when I try to add data to my array (JSON). I don't have fixed dimension of array, it my be 2 or more dimension (I am building a model for Web form, and I want to add invalid value to JSON).
Now in one of the methods of Web form object I have code which checks repopulation object to add invalid value if needed.
I can not just add a value to JSON array, I need to edit it on multidimensional level.
For now I came up on solution to dynamically generate variable name and, then, edit it. If someone have solution it will be appreciated.
private $form = array(
'form_contact'=>array(
'attr'=>array('tag'=>'FORM', 'method'=>'post'),
'elem'=>array(
'fs_contact'=>array(
'attr'=>array('legend'=>'Kontakt', 'tag'=>'FSET'),
'elem'=>array(
'name'=>array(
'attr'=>array('SPAN'=>'Ime i prezime', 'title'=>'Unesite Vaše ime i prezime', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'noscript', 'length'=>255),
'invalid'=>true), // Holds info that this is invalid
'www'=>array(
'attr'=>array('SPAN'=>'Web sajt', 'title'=>'Unesite Vaš sajt', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('length'=>255)),
'email'=>array(
'attr'=>array('SPAN'=>'E-mail', 'title'=>'Unesite Vaš email', 'tag'=>'INPUT', 'type'=>'text'),
'validat'=>array('req'=>'email', 'length'=>255)),
'message'=>array(
'attr'=>array('SPAN'=>'Poruka', 'cols'=>'60', 'rows'=>'5', 'title'=>'Unesite Vašu poruku', 'tag'=>'TEXTA', 'value'=>'nesto'),
'validat'=>array('req'=>'all')),
'submit_new_contact_form'=>array(
'attr'=>array('tag'=>'INPUT', 'type'=>'submit', 'value'=>'Pošalji poruku!'))
))// FS end
)) // Form end
);// Array end
You can't do it that way, as PHP thinks you're looking for a variable with the name $a['i'], rather than the 'i' key in the $a array.
The proper, and conventional, way is to use a dynamic key/index instead:
$b = 'i';
echo $a[$b];

Categories