Any of the following are valid:
$myArray = array();
$myArray[] = new Object();
$myArray[1] = new Object();
array_push($myArray, new Object);
Answer from Byron Whitlock on Stack OverflowAny of the following are valid:
$myArray = array();
$myArray[] = new Object();
$myArray[1] = new Object();
array_push($myArray, new Object);
Try this,
$obj = array(new stdClass(), new stdClass())
or
$obj = array()
$obj[] = new stdClass()
$obj[] = new stdClass()
EDIT:
Class to stdClass
What you should probably do is:
$hotelsDetail = array();
$details = new HotelDetails();
$details->setHotelInfo($rs);
$details->setPrice('150');
// assign it to the array here; you don't need the [0] index then
$hotelsDetail[] = $details;
In your specific case, the issue is that you should use ->, not .. The period isn't used in PHP to access attributes or methods of a class:
$hotelsdetail[0] = new hoteldetails();
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
Note that I capitalized the class, object, and function names properly. Writing everything in lowercase is not considered good style.
As a side note, why is your price a string? It should be a number, really, if you ever want to do proper calculations with it.
You should append to your array, not assign to index zero.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
This will append the object to the end of the array.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
This would create an array with three objects, appending each one successively.
Additionally, to correctly access an objects properties, you should use the -> operator.
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.
Example 1
PHP
$php = array(1,2,3,4,5,6,7,8,9,10);
for (
i < 10 ; $i ++)
echo
i]."<br>";
Python (generally you iterate over lists in Python, instead of accessing by index):
lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
print(str(item) + "<br>")
Example 2
for (
i < 10 ; $i ++)
echo
i] = $i +1 ;
Python:
lst = range(1, 11)
for item in lst:
print(item)
Or maybe:
lst = []
for i in range(10):
lst.append(i + 1)
print(lst[-1]) # prints out last element
Example 3
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach (
value)
echo $value."<br>";
Same as 1st
Example 4
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
Python:
lst = [1, 2, 3, 4]
lst = [val * 2 for val in lst]
Example 5
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach (
key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
Python (note that {...} creates a dict [dictionary] in Python, not a list/):
dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.items():
print("Key: %s; Value: %s<br />" % (key, value))
Example 6
$arr = array("one", "two","three");
while (list(
value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
Python:
lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
print("Key: %d; Value: %s<br />" % (key, value))
Example 7
$arr = array("one", "two","three");
while ($element = each($arr)) {
echo "Key: $element['key']; Value: $element['value']<br />\n";
}
There is no direct Python equivalent to this.
Example 8
$products = array( array("ITL","INTEL","HARD"),
array("MIR", "MICROSOFT","SOFT"),
array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
);
for (
row < 3; $row++)
{
for ($col = 0;
col++)
{
echo "|".$products[
col];
}
echo "<br>";
}
Python:
products = [['ITL', 'INTEL', 'HARD'],
['MIR', 'MICROSOFT', 'SOFT'],
['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]
for product in products:
for item in product:
print('|' + item)
print('<br>')
Or maybe a more Pythonic version:
for product in products:
print('|%s<br>' % ('|'.join(product)))
"What is in Python?", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than right now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
Sorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.
Unless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.
Still not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad.
In the simplest case, it's probably sufficient to "cast" the array as an object:
$object = (object) $array;
Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:
$object = json_decode(json_encode($array), FALSE);
This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.
Warning! (thanks to Ultra for the comment):
json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL
you can simply use type casting to convert an array to object.
// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;
//now it is converted to object and you can access it.
echo $object->username;
In your python script do something like
import json
#some code here
jsonStr = json.dumps(myListFromGooglePlaces)
#whatever you do to get it to php
and then as mentioned in my comment above
$arr = json_decode($json, true);
I hope that works for you.
You could use json_decode function
j_obj = '[{ ....}]';
$array = json_decode($j_obj,true);
This code
$pages_array[1]->slug = "a";
is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:
$pages_array[] = new MyObject('index', 'title'....)
or using a stdclass cast
$pages_array[] = (object) array('slug' => 'xxx', 'title' => 'etc')
If you make them arrays with named keys rather than objects, you can do it like this:
$pages_array = array(
array(
'slug' => 'index',
'title' => 'Site Index',
'template' => 'interior'
),
array(
'slug' => 'a',
'title' => '100% Wide (Layout A)',
'template' => 'interior'
),
array(
'slug' => 'homepage',
'title' => 'Homepage',
'template' => 'homepage'
)
);
You can combine this with Fanis' solution and use the slugs as the keys if you like.