I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.
The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.
I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.
Array (
[is_error] => 0
[version] => 3
[count] => 2
[values] => Array (
[556053] => Array (
[contact_id] => 556053
[contact_type] => Individual
[first_name] => Brian
[last_name] => YYY
[contact_is_deleted] => 0
)
[596945] => Array (
[contact_id] => 596945
[contact_type] => Individual
[first_name] => Brian
[last_name] => XXX
[contact_is_deleted] => 0
)
)
)
I've looked at the following post, but it seems to only address the situation where the array indices are sequential.
Multidimensional array - how to get specific values from sub-array
Any ideas?
Brian
You are correct in your assumption. You could do something like this:
foreach($array['values'] as $key => $values) {
print $values['contact_id'];
}
That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.
Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:
$a['values'][556053]['contact_id']
and here:
$a['values'][596945]['contact_id']
So if there's no additional structure in your array, then this loop is probably what you want:
foreach ($a['values'] as $toplevel_id => $record_data) {
print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}
foreach($array['values'] as $sub_arr){
echo $sub_arr['contact_id'];
}
Related
i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.
I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]
Just a quick one i need to get a value from an array the array is made like this
$resultOfAdd[“CaseAndMatterResult”][“ResultInfo”][“ReturnCode”];
and it gives an output of this
Array (
[AddCaseAndMatterResult] => Array (
[ResultInfo] => Array (
[ReturnCode] => OK
[Errors] =>
[Warnings] =>
)
[CaseID] => 4880062
[MatterID] => 4950481
[LeadID] => 0
[CustomerID] => 0
)
)
All i want to do is put the part "MatterID" into a variable. how would I achieve this.
i have tried
$matterID = array($resultOfAdd["MatterID"]);
and this does not work
Regards
This is a multi-dimensional, associative array. Think of it like floors of a building. The key MatterID does not live in the first dimension (floor), rather on the second, in the AddCaseAndMatterResult sub-array.
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID']
Successive dimensions of an array are specified with successive square-brackets, each naming the key to look in (this is true of most languages).
$matterID = $yourArray['AddCaseAndMatterResult']['MatterID'];
Use this way:
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID'];
I'm a bit struggling with the associative arrays in associative arrays. Point is that I always have to drill deeper in an array and I just don't get this right.
$array['sections']['items'][] = array (
'ident' => $item->attributes()->ident,
'type' => $questionType,
'title' => $item->attributes()->title,
'objective' => (string) $item->objectives->material->mattext,
'question' => (string) $item->presentation->material->mattext,
'possibilities' => array (
// is this even neccesary to tell an empty array will come here??
//(string) $item->presentation->response_lid->render_choice->flow_label->response_label->attributes()->ident => (string) $item->presentation->response_lid->render_choice->flow_label->response_label->material->mattext
)
);
foreach ($item->presentation->response_lid->render_choice->children() as $flow_label) {
$array['sections']['items']['possibilities'][] = array (
(string) $flow_label->response_label->attributes()->ident => (string) $flow_label->response_label->material->mattext
);
}
So 'possibilities' => array() contains an array and if I put a value in it like the comment illustrates I get what I need. But an array contains multiple values so I am trying to put multiple values on the position $array['sections']['items']['possibilities'][]
But this outputs that the values are stores on a different level.
...
[items] => Array
(
[0] => Array
(
[ident] => SimpleXMLElement Object
(
[0] => QTIEDIT:SCQ:1000015312
)
[type] => SCQ
...
[possibilities] => Array
(
)
)
[possibilities] => Array
(
[0] => Array
(
[1000015317] => 500 bytes
)
[1] => Array
...
What am trying to accomplish is with my foreach code above is the first [possibilities] => Array is containing the information of the second. And of course that the second will disappear.
Your $array['sections']['items'] is an array of items, so you need to specify which item to add the possibilities to:
$array['sections']['items'][$i]['possibilities'][]
Where $i is a counter in your loop.
Right now you are appending the Arrays to [items]. But you want to append them to a child element of [items]:
You do:
$array['sections']['items']['possibilities'][] = ...
But it should be something like:
$array['sections']['items'][0]['possibilities'][] = ...
$array['sections']['items'] is an array of items, and as per the way you populate the possibilities key, each item will have it's own possibilities. So, to access the possibilities of the item that is being looped over, you need to specify which one from $array['sections']['items'] by passing the index as explained in the first answer.
OR
To make things simpler, you can try
Save the item array (RHS of the first =) to a separate variable instead of defining and appending to the main array at the same time.
Set the possibilities of that variable.
Append that variable to the main $array['sections']['items']
I have:
array[{IsChecked: true, SEC: 0, STP: 0},
{IsChecked: ture ,SEC: 0, STP: 1},
{IsChecked: false, SEC: 1 ,STP: 0}]
How to get each SEC where IsCheked value is true?
I have some data for my sites statistics in a SQL DB:
date: visits: pageviews:
12-12-12 34 21
12-12-13 31 22
12-12-14 33 2445
12-12-15 35 2422
12-12-16 36 232
//ect ect
I'm trying to create a Multidimensional array that contains all the dates info from the DB and where the date will be the key (selector,name of the array inside the multi array), so as the end result, I should be able to just do this:
print_r $my_multi_array[12-05-12];
And I should see the statistics for that date on the screen.
Now I know how to do all the loops and stuff, and I even have a good idea about how to do multidimensional arrays, it's just that I think I'm doing something wrong:
//first things first, define the array:
$my_multi_array=array();
//then, in a loop, append to the array:
$my_multi_array[]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));
Now when I print_r that array, everything looks good:
Array ( [0] => Array ( [11-12-24] => Array ( [visits] => 1 [pageviews] => 0) ) [1] => Array ( [11-12-25] => Array ( [visits] => 1 [pageviews] => 0) ) [2] => Array ( [11-12-26] => Array ( [visits] => 1 [pageviews] => 0)))1
Notice the 1 at the end ^^. That seemed to be in the result (not a typo).
Now when I try printing a certain array out (using the date as the key):
print_r $my_multi_array['11-12-24'];
I get:
1
So then i try:
print_r $my_multi_array[2];
and that works fine.
For some reason, it wont let me select an array from $my_multi_array using the date as the key.
Any ideas on how to fix this?
thanks
Everything is correct, because you don't have array('key' => 'value') style array, instead of that you've got array( [0] => array( 'key' => 'value' ) ) that's why you're getting correct result on accessing numeric key of the array.
You have to put the date as the array key, like so:
$my_multi_array[$date]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));
Notice the $my_multi_array[$date].
By doing $my_multi_array[] = ... you are just creating a new numerical index on the array with the content on the right side. That's why when you access the array with the numerical index, like $my_multi_array[2], it works.
On the other hand, by doing $my_multi_array[$date]you are treating the array like an hash table, where you associate a key (in this case a string containing a date) with a value.