Reputation: 179
Let me explain my problem, I am supposed to call a web service before the contact form is shown, the return of the web service is:
$items = json_decode('[{"location":[{"building":["Building1"],"name":"Location1"}],"name":"Organization1"},{"location":[{"building":["Building2"],"name":"location2"}],"name":"Organisation2"},{"location":[{"building":["Building3"],"name":"Location3"}],"name":"Organization3"}]');
Here I have extracted only the organisations,locations and building using the following code:
foreach( $items as $each ){
echo $each->location[0]->building[0];
echo $each->location[0]->name;
echo $each->name;
}
I would like to get the values of organisations, buildings and locations in different arrays in this format:
("building1", "building2", "building3")
("organisation1", "organisation2", "organisation3")
("location1", "location2", "location3")
Upvotes: 1
Views: 109
Reputation: 46249
To take your existing code and modify it a tiny bit;
$buildings = array( );
$organisations = array( );
$locations = array( );
foreach( $items as $each ){
$buildings[] = $each->location[0]->building[0];
$organisations[] = $each->location[0]->name;
$locations[] = $each->name;
}
The results are now in the variables defined at the top. []
simply tells it to append a value to the end of the array.
Upvotes: 1
Reputation: 76240
Here's how you do it:
$arrays = array();
$arrays['buildings'] = array(); // buildings
$arrays['organisations'] = array();
$arrays['locations'] = array();
foreach( $items as $each ){
$arrays['buildings'][] = $each->location[0]->building[0];
$arrays['organisations'][] = $each->location[0]->name;
$arrays['locations'][] = $each->name;
}
Upvotes: 0