I asked a similar question earlier but I haven't been able to find anything to help me. I have now updated my code to something working but I am now completely stuck.
This is my php code:
class person {
public $name;
public $SE;
private $SD;
function __construct ( $n, $s1, $s2 ) {
$this->name = $n;
$this->SE = $s1;
$this->SD = $s2;
}
}
$Obj = new person ( "ExampleName", 5, 5 );
I need to have seperate divs created for each person, containing their names in these divs. My main problem is that after these divs are created I need to have them sorted in a particular way (that isn't any importance to you) that requires for each div to have a ID associated to the original person from which the div was created.
I am otherwise able to create divs from a list of names but not from objects.
So:
I need a way to use foreach loops to create divs according to each object (person).
I need these divs associated with (linked to) that person.
Thanks for any help
Not sure what you mean by divs associated with that person but for first problem this should work.
Lets say you have an array of objects named $objs
foreach($objs as $obj)
{
echo "<div>".$obj->name."</div>";
}
I'm not sure this is what you're looking for, but this should work:
// create an array of persons, I'm assuming that SE or SD is
// unique for each object
$persons = (
new person("Allan", 1, 1);
new person("Bobbo", 2, 2);
new person("Cicci", 3, 3)
);
The objects could be sorted by name using usort()
:
usort($persons, function($a, $b) {
return $a->name > $b->name;
});
// loop through each object and output a div
// notice that the id will be unique and based on
// the `SE` member of the object, you can then reference
// a specific div from javascript $('#person-1') etc
foreach ($persons as $person) {
print '<div class="person" id="person-' . $person->SE . '">' . $person->name . '</div>';
}
Using jQuery
you could then get an object based on the unique id:
$(document).ready(function() {
$('.person').click(function() {
$.ajax('object.php', {
type: 'post',
data: 'id=' + $(this).attr('id').substr(7),
dataType: 'json',
success:function(obj) {
alert('You clicked on ' + obj.name + ' ' + obj.SE + ' ' + obj.SD);
}
});
});
});
You would search in you $persons
array to find the object with a corresponding SE
(or whatever you deside to use as the unique identifer) value:
// object.php
if (isset($_POST['id'])) {
$id = intval($_POST['id']);
foreach ($persons as $person) {
if ($person->SE == $id) {
// return json object
print json_encode($person);
break;
}
}
}