I am having some troubles calling the correct values in the php array. Here is the array.
Array ( [count] => 1 [threads] => Array ( [13] => Array ( [thread_id] => 13 [node_id] => 4 [title] => Forum Integration nearly complete! [reply_count] => 0 [view_count] => 0 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [sticky] => 0 [discussion_state] => visible [discussion_open] => 1 [discussion_type] => [first_post_id] => 23 [first_post_likes] => 0 [last_post_date] => 1369257302 [last_post_id] => 23 [last_post_user_id] => 59 [last_post_username] => Faeron [prefix_id] => 1 [content] => Array ( [count] => 1 [content] => Array ( [23] => Array ( [post_id] => 23 [thread_id] => 13 [user_id] => 59 [username] => Faeron [post_date] => 1369257302 [message] => It's been quite a while since we began to integrate the phanime Forums with the main site. We have now finished the integration with the phanime Forums and the main site. You will no longer notice that there are two platforms running phanime, but instead only one. Our next step is to theme the forums to make it look like the main site! [ip_id] => 268 [message_state] => visible [attach_count] => 0 [position] => 0 [likes] => 0 [like_users] => a:0:{} [warning_id] => 0 [warning_message] => ) ) ) ) ) )
Now lets say this array was named $array then to get the first element's value "[count]" can't I just say the following: print $array["[count]"] <-- this returns an error.
What about the element that has a value as an array itself, which is the [threads] element. How do I get, perhaps the [thread_id] element's value?
Use it like this:
echo $array['count']; // would output '1'
echo $array['threads'][13]['thread_id']; // outputs '13'
echo $array['threads'][13]['content']['content'][23]['message']; // "It's been.."
Here is the (brief) documentation on multidimensional arrays: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.accessing
Here's a good guide to them with examples: http://www.developerdrive.com/2012/01/php-arrays-array-functions-and-multidimensional-arrays/
Update: To get the value of 'message' without knowing the numbered array keys beforehand you could use:
reset($array);
$first = array_keys($array['threads']);
$first = $first[0];
$second = array_keys($array['threads'][$first]['content']['content']);
$second = $second[0];
echo $array['threads'][$first]['content']['content'][$second]['message'];
You can access a value in an array by using the following:
echo $array['count'];
You can also print the entire array like so:
print_r($array);
or
var_dump($array);
If you want to write a value from a multidimensional array then use the following:
echo $array[23]['post_id'];
So, to summarize, see the following:
$array = array(
'bar' => 'testing value',
'foo' => array(
'bar' => 'test'
)
);
print_r($array) // Will print whole array
echo $array['bar']; // Will print 'testing value'
print_r($array['foo']); // Will print the second level array
echo $array['foo']['bar']; // Will print 'test'
Related
I have this multi-dimensionnal array called $response (I only get one result but there are many in reality..)
Array
(
[took] => 17
[timed_out] =>
[_shards] => Array
(
[total] => 5
[successful] => 5
[skipped] => 0
[failed] => 0
)
[hits] => Array
(
[total] => 16
[max_score] => 13.034995
[hits] => Array
(
[0] => Array
(
[_index] => zh3
[_type] => zone_humide
[_id] => 4950467
[_score] => 13.034995
[_source] => Array
(
[surfcal_ha] => 2.26
[#timestamp] => 2019-01-21T19:25:48.826Z
[#version] => 1
[donnee_id] => 3355
[zhu_cbi] => 82
[zh_nom] => Coupigny
[gid] => 4950467
[zh_part_id] => 079FONTEN0011
[is_pe] =>
)
)
)
)
)
I want to get the gid attribute. To do that, I tried :
foreach ($response['hits']['hits'][0]['_source'] as $result) {
echo $result['gid'];
}
But I get that PHP Warning :
PHP Warning: Illegal string offset 'gid'
I tried different things.. add another foreach loop, change the echo but nothing works. I tried that coming from StackOverflow but no results too. Well I think I'm really stuck.
Any ideas on that problem ?
Any help would be very appreciated !
Thanks
$response array has only one parent element. Why do you use foreach?
Just try
echo $response['hits']['hits'][0]['_source']['gid'];
it is because you are using foreach on $response['hits']['hits'][0]['_source']
eg. 1.in first loop of foreach it will get$result['surfcal_ha']
2. in second loop it is getting $result[#timestamp]
so till it doesnt get $result['gid'] it will print warning.Try using below without foreach
echo $response['hits']['hits'][0]['_source']['gid'];
Quick question, how do you echo a variable when the array has key's that contain names with brackets etc. See array below:
[data] => Array
(
[0] => stdClass Object
(
[id] => 4
[contact_id] =>
[status] => Complete
[is_test_data] => 0
[datesubmitted] => 2014-04-16 22:18:39
[sResponseComment] =>
[responseID] => 4
[[question(1), option(0)]] =>
[[question(2)]] => John
[[question(3)]] => Wtf#wtf.com
[[question(5)]] => 0975735289
[[question(6)]] => 3010
[[question(9), option(0)]] =>
[[question(10)]] => Testing
[[question(11)]] => Later
[[question(12)]] => This year
)
Lets say i want to echo the answer to question 2, which is "John". How do i go about doing this?
Well you have an array conataining an array of objects:
echo $array['data'][0]->{'[question(2)]'};
I have this:
print_r($response["member"]);
I need to retrieve name under levels, it's at the bottom, how should I write it:
I thought of $response["member"][0]["Sequential"]["levels"]...? Also this number under levels wont be always the same.
Thank you!
Array
(
[0] => Array
(
[ID] => 1
[UserInfo] => Array
(
[ID] => 1
[caps] => Array
(
[administrator] => 1
)
[cap_key] => wp_capabilities
[roles] => Array
(
[0] => administrator
)
[allcaps] => Array
(
[switch_themes] => 1
[edit_themes] => 1
[activate_plugins] => 1
[edit_plugins] => 1
[edit_users] => 1
[edit_files] => 1
[manage_options] => 1
[moderate_comments] => 1
[manage_categories] => 1
[manage_links] => 1
[upload_files] => 1
[import] => 1
[unfiltered_html] => 1
[edit_posts] => 1
[edit_others_posts] => 1
[edit_published_posts] => 1
[publish_posts] => 1
[edit_pages] => 1
[read] => 1
[level_10] => 1
[level_9] => 1
[level_8] => 1
[level_7] => 1
[level_6] => 1
[level_5] => 1
[level_4] => 1
[level_3] => 1
[level_2] => 1
[level_1] => 1
[level_0] => 1
[edit_others_pages] => 1
[edit_published_pages] => 1
[publish_pages] => 1
[delete_pages] => 1
[delete_others_pages] => 1
[delete_published_pages] => 1
[delete_posts] => 1
[delete_others_posts] => 1
[delete_published_posts] => 1
[delete_private_posts] => 1
[edit_private_posts] => 1
[read_private_posts] => 1
[delete_private_pages] => 1
[edit_private_pages] => 1
[read_private_pages] => 1
[delete_users] => 1
[create_users] => 1
[unfiltered_upload] => 1
[edit_dashboard] => 1
[update_plugins] => 1
[delete_plugins] => 1
[install_plugins] => 1
[update_themes] => 1
[install_themes] => 1
[update_core] => 1
[list_users] => 1
[remove_users] => 1
[add_users] => 1
[promote_users] => 1
[edit_theme_options] => 1
[delete_themes] => 1
[export] => 1
[administrator] => 1
)
[filter] =>
[user_login] => admin
[user_nicename] => admin
[user_email] => goranefbl#gmail.com
[user_url] =>
[user_registered] => 2014-01-29 10:57:09
[user_activation_key] =>
[user_status] => 0
[display_name] => admin
[wlm_feed_url] => http://pialarson.com/excel/feed/?wpmfeedkey=1;2e7e48ca65d94e5f0ec1baae46e4972c
[wpm_login_date] => 1392155735
[wpm_login_ip] => 62.68.119.252
)
[Sequential] =>
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
[ExpiryDate] => 1393866766
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1391447566
[TxnID] => WL-1-1391447566
)
)
[PayPerPosts] => Array
(
)
)
)
An answer might be to use array_walk_recursive by following the official documentation:
http://www.php.net/manual/en/function.array-walk-recursive.php
<?php
$properties = new stdClass();
$properties->names = [];
function extractNames($levels, $key, $properties) {
if (
is_object($levels) &&
array_key_exists('Name', get_object_vars($levels)) &&
array_key_exists('Level_ID', get_object_vars($levels))
) {
$properties->names[] = $levels->Name;
}
}
array_walk_recursive($response, 'extractNames', $properties);
echo print_r($properties, true);
<?php
$nameInFirstLevelsElement = current($response["member"][0]["levels"])->Name
?>
This should work to retrieve the Name from the first levels element.
That empty space next to "Sequential" means it doesn't have a value. So that's not the one you're looking for.
Furthermore, one of those levels indicates "stdClass object", which means you can access its members via the -> operator.
Let's strip away everything that doesn't matter for a minute. I think it'll help you understand the data structure:
Array
(
[0] => Array
(
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
)
)
)
)
So this will work:
$object = $response["member"][0]["Levels"][1391447566];
$name = $object->Name;
Edit
If the index of Levels changes every time, then pull it apart a little bit more...
$levels = $response["member"][0]["Levels"];
$firstLevel = array_shift(array_values($levels));
$name = $firstLevel->Name;
See here for a good answer on getting the first element out of the $levels array: https://stackoverflow.com/a/3771228/266374
If the number under the 'Levels' array won't be the same, you can use a foreach to pull out the 'Name' information.
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_key->Name;
}
echo 'Name: '.$level_name;
If there is only going to be one element, then it will grab it. If there are multiple numbers under 'Levels', then it will loop through them and assign each one to '$level_name', overwriting any previous assignments. In other words, only the last one it finds will be captured.
EDIT:
In the example, I mistakenly tried to grab the Name from the $key instead of the $val. This is the correct method:
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_val->Name;
}
echo 'Name: '.$level_name;
Here is a demo of the working code
I am not really familiar on how php handles array, in .NET I can access array using this method
array[x][y];
My question is:
I am retrieving records from the database and returning it to the $res_merchant_field
$res_merchant_field = $this->CI->merchantfield_model->merchantfield_list( $str_where );
and $res_merchant_field will be populated with this record:
Array
(
[0] => stdClass Object
(
[MFID] => 1
[MFName] => Bill No
[FTID] => 1
[DTID] => 1
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 0
[MFMaxLength] => 12
[MFOrderNo] => 1
[MFStatus] => 1
)
[1] => stdClass Object
(
[MFID] => 2
[MFName] => Gallons Consumed
[FTID] => 1
[DTID] => 2
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 0
[MFMaxLength] => 5
[MFOrderNo] => 2
[MFStatus] => 1
)
[2] => stdClass Object
(
[MFID] => 3
[MFName] => Amount Due
[FTID] => 3
[DTID] => 1
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 1
[MFMaxLength] => 15
[MFOrderNo] => 3
[MFStatus] => 1
)
)
How can I access and fetch the record from that array with this condition:
it will look through all the array find specific index, lets say index 0 which is MFID,
after getting the MFID and comparing it with another variable, if it is true,
it will get the DTID for that array MFID.
example:
get MFID = 1, the DTID will be 1, if I get the MFID = 3, the DTID will be 1.
or how can I access the array like $array[x][y]?
Thanks in advance.
The problem is that the second level is not an array but instead an object, to access a property you will have to use this format.
$array[$x]->$y;
Unfortunately you cannot access a property by an index do o get the MFID of the 0th Item you will need to say
$array[0]->MFID;
I've had to ask this one again, sorry, but I'm having a problem trying to process this array. I have tried several different ways but none where right, here's the array:
Array (
[search] => Array (
[response] => Array (
[errors] =>
[number_of_hotels] => 1 of 1
)
[lr_rates] => Array (
[hotel] => Array (
[hotel_ref] => 3116
[hotel_currency] => [U] => USD
[hotel_rooms] => Array (
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
[room] => Array (
[ref] => 6382
[type] => 1
[type_description] => Standard
[sleeps] => 8
[rooms_available] =>
[adults] => 8
[children] =>
[breakfast] => false
[dinner] => false
[description] =>
[alternate_description] =>
[rack_rate] => 82.01
[date] => 19/08/201220/08/201221/08/2012
[numeric_hotelcurrencyprice] => FullFullFull
[formatted_date] => 19 August 201220 August 201221 August 2012
[price] => FullFullFull
[hotelcurrencyprice] => FullFullFull
[numeric_price] => FullFullFull
[requested_currency] => GBPGBPGBP
[numeric_hotelcurrencyprice] => FullFullFull
[available_online] => false
[minimum_nights] => 1
[bed_type] =>
[cancellation_policy] =>
[cancellation_days] =>
[cancellation_hours] =>
[room_terms] =>
)
)
[cancellation_type] => First Night Stay Chargeable
[cancellation_policy] => 2 Days Prior to Arrival
[CityTax] => Array (
[TypeName] =>
[Value] =>
[OptedIn] =>
[IsCityTaxArea] =>
)
)
)
)
)
Ok, I need to traverse the array and create a loop, so for every instance of ROOM it will repeat the process. Then i need to extract the data from room array and use it to populate rows in MySQL for each instance of room.
This is the code I have so far which prints the names and values in the room array. However, it only gets one of the room arrays. What can I do to read all of the rooms? I am also thinking this is too many for-each but don't seem to be able to traverse down ['']['']['']...
or by just using the associative name.
foreach($arr['search'] as $lr_rates) {
foreach($lr_rates['hotel'] as $hotel) {
foreach($hotel['room'] as $field => $value){
print $field;print $value;
}
}
}
It might also be worth mentioning the values in these arrays are always fluctuating.
I think you can really simplify this quote a bit. If you know that this will always be the structure then you can jump right down into the hotels and then into the rooms.
foreach($arr['search']['lr_rates']['hotel'] as $hotel) {
// You can access all of the keys in the hotel array here
foreach($hotel['hotel_rooms'] as $room) {
// Do stuff with the room array
}
}
I would recommend either building your insert script on the fly and calling the database just once for the write, or if you are updating then using a transaction. As the number of rooms gets larger you will slow your script down with a bunch of writes to disk.
the formatting of your data's output is very bad and unreadable. I cannot really identify what you are trying to do.
possibility: the inner array [hotel_rooms] => Array () uses the key room multiple times. as array keys are unique, you overwrite the data at the index room. this is why you only get one room.
possibility: there are rooms inside a room -> use a recursive function to iterate over all rooms like this:
function handleRoom(array $room) {
// do something with $room
if (array_key_exists('room', $room)) {
handleRoom($room['room']);
}
}
$room = array(
'some' => 'room',
'data' => 'and another',
'room' => array(
'is' => 'inside',
'of the' => 'main room',
),
);
handleRoom($room);