I've got this array:
array(1) {
["sensory-evaluation"]=> array(6) {
["name"]=> string(18) "Sensory Evaluation"
["value"]=> string(43) "10/22/2015 at 6:00pm | 11/25/2015 at 6:00pm"
["position"]=> string(1) "3"
["is_visible"]=> int(1)
["is_variation"]=> int(1)
["is_taxonomy"]=> int(0)
}
}
I need to be able to get the data from ["value"]. If I do $arr["sensory-evaluation"]["value"] I can get it but the problem is ["sensory-evaluation"] will be different for each element in my array so I need a way to abstract that part but I haven't been able to figure it out.
If you have only one item in the array as you show then:
echo current($arr)['value'];
If you don't know if it exists:
if(isset(current($arr)['value'])) {
echo current($arr)['value'];
}
You could also do:
echo array_values($arr)[0]['value'];
why not use a for each
function getValue($arr){
foreach ($arr as $key => $value) {
var $subArray=$arr[$key];
if( array_key_exists ('value' ,$subArray))
return $arr[$key]['value'];
}
}
Related
I'm currently getting a JSON response from a company's API and converting it into a PHP array like this:
$api_url = file_get_contents('http://example.com');
$api_details = json_decode($api_url, true);
When I run var_dump on $api_details, I am getting this:
array(2) {
["metadata"]=>
array(5) {
["iserror"]=>
string(5) "false"
["responsetime"]=>
string(5) "0.00s"
["start"]=>
int(1)
["count"]=>
int(99999)
}
["results"]=>
array(3) {
["first"]=>
int(1)
["result"]=>
array(2) {
[0]=>
array(4) {
["total_visitors"]=>
string(4) "3346"
["visitors"]=>
string(4) "3249"
["rpm"]=>
string(4) "0.07"
["revenue"]=>
string(6) "0.2381"
}
[1]=>
array(4) {
["total_visitors"]=>
string(6) "861809"
["visitors"]=>
string(6) "470581"
["rpm"]=>
string(4) "0.02"
["revenue"]=>
string(7) "13.8072"
}
}
}
}
I'm trying to do 2 things and can't figure out how to do either with a multidimensional array.
I need to check to see if metadata > iserror is false. If it is not false, I want to show an error message and not continue with the script.
If it is false, then I wants to loop through the results of results > result and echo the total_visitors, visitors, etc for each of them.
I know how to echo data from array, I guess I'm just getting confused when there's multiple levels to the array.
Anyone that can point me in the right direction would be much appreciated :)
You can iterate over arrays using foreach. You can read up on it here: http://php.net/manual/en/control-structures.foreach.php
Since you're using associative arrays, your code will look something like this:
if ($arr['metadata']['iserror']) {
// Display error here
} else {
foreach($arr['results']['result'] as $result) {
echo $result['total_visitors'];
echo $result['visitors'];
}
}
You'll have to tweak the code to fit exactly what you're doing, but this should get you over the line.
Hope that helps!
i have output from query
object(stdClass)#14 (6) {
["aid"]=>
string(2) "11"
["bid"]=>
string(2) "34"
["colorname"]=>
string(6) "Silver"
["colorgroupname"]=>
string(15) "LIGHT AQUA OPAL"
["colorcode"]=>
string(3) "6M8"
["brand"]=>
string(6) "Car"
}
but after loop in foreach
complite code what i use and i use var_dump to display output i get one rows but after loop i get 6 duplicate rows.
function ViewDBGridColorfinder($header,$DBG_control,$parameters)
{
$rows = $this->select_join_by(index_join_ColorFinder,TBL_COLOR,tbl_join_ColorFinder,where_by,order_by_dbgrid,$parameters);
$table = new Generator_Table($header);
//var_dump($rows);
if (is_array($rows) || is_object($rows))
{
foreach($rows as $val)
{
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
}
}
$DBGrid_data = $table->generate();
return $DBGrid_data;
}
the result to be duplicate.
where is the error?
I think this sholud only do for you
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
Remove foreach as.
Replace all $rows with $val in foreach loop
You used the variable $rows itself instead of $val. Update the code like this:
foreach($rows as $val)
{
$DetailColor = ''.$val->colorname.'';
$table->addCell($DetailColor);
$table->addCell($val->colorcode);
$table->addCell($val->brand);
$table->addCell($val->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$val->aid.")",$DBG_control));
}
Your $row is an object. So you don't really need to forloop inside the object. The reason why your getting 6 records is because there are six elements inside your object.
Count this and see, There are 6 elements(aid,bid,colorname,colorgroupname,colorcode,brand):
object(stdClass)#14 (6) {
["aid"]=>
string(2) "11"
["bid"]=>
string(2) "34"
["colorname"]=>
string(6) "Silver"
["colorgroupname"]=>
string(15) "LIGHT AQUA OPAL"
["colorcode"]=>
string(3) "6M8"
["brand"]=>
string(6) "Car"
}
So for each element, it will add the cell.In PHP you can use the -> to access the elements inside the object. Modify the code this way:
if (is_array($rows) || is_object($rows))
{
$DetailColor = ''.$rows->colorname.'';
$table->addCell($DetailColor);
$table->addCell($rows->colorcode);
$table->addCell($rows->brand);
$table->addCell($rows->colorgroupname);
$table->addCell(str_replace('onclick=""',"onclick=DelRow(".$rows->aid.")",$DBG_control));
}
Hello I am looking for some help with removing an element from an array. My array $rooms holds events per rooms. Each room has its own array and each event has its own array within the room array. I loop through $rooms and display the room ID and within this loop I loop through the events for that room and display their contents. I would like to remove the array for the event that has been displayed so I don't have spend time comparing it when I repeat the same loop.
Below is an example of the process I am describing. I know it makes no sense to delete the element in this logic as I am using foreach, but within my application the logic of the function requires it..
$rooms
array(3)
{
[1]=> array(2)
{
["rid"]=> string(1) "1"
["events"]=> array(0)
{ }
}
[2]=> array(2)
{
["rid"]=> string(1) "2"
["events"]=> array(0)
{ }
}
[3]=> array(2)
{
["rid"]=> string(1) "3"
["events"]=> array(2)
{
[0]=> array(7)
{
["lname"]=> string(20) "xxxxxxxxxxxxxxxxxxxx"
}
[1]=> array(7)
{
["lname"]=> string(10) "yyyyyyyyyy"
}
}
}
}
loop
foreach ($rooms as $room):
echo $room['rid'];
foreach ($room['events'] as $event):
echo $event['lname'];
If you could tell me where within the foreach I should put the code and how should the code look like that would be really great. I think it should be right after echo $event['lname'], but I can't figure out how to locate the element that is displayed so I can unset it..
Thank you all for reading,
looking forward to your replies.
You can simply unset the event after echoing it, but you'll need to reference it from $rooms, so you need to use the key's at each level. Try this:
foreach($rooms as $i => $room) {
echo $room['rid'];
foreach($room['events'] as $j => $event) {
echo $event['lname'];
unset($rooms[$i]['events'][$j]);
}
}
You can see an example of it working here.
I have a $date array like this:
[1]=> array(11) {
["meetingname"]=> string(33) "win2008connectcurrent0423131"
[0]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
[1]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 14:40:06"
["numparticipants"]=> string(1) "3"
}
}
foreach($date[0] as $key => $meetings){
print "$key = $meetings\n";////yields scoid = 3557012
}
And, as you can see above, I am looping over individual elements. The first element (not indexed) is always meetingname; the rest of the elements are indexed and themselves contain arrays with three elements in each array--in the above code they are [0] and [1].
What I need to do is make the $meetings as an array containing [0] and then [1] etc, depending on the number of elements. So essentially, the output for print should be an array (I can also use var_dump) with key/values of [0] but right not it only outputs individual keys and their values, for example, as you can see above, scoid=3557012. I will need, something all keys/values in the $meetings variable, something like:
{
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
How can I fix the foreach loop for that?
please Try this. hope it help.
foreach($date as $key => $meetings){
if($key == "meetingname")
continue;
else
print "$meetings\n";
}
You can just create a new array and add the meetings to that one
<?php
$meetings = array();
foreach($date[1] as $key=>$meeting) {
if (!is_int($key))
continue; //only handle numeric keys, incase you ever change the name of the first key 'meetingname'
$meetings[] = $meeting
}
var_dump($meetings);
?>
I am still very new to PHP and from all the examples that are around they all seem to use foreach statements.
e.g.
foreach ($variable as $row)
However I don't think I should be using this all the time, for example variables or objects I have an which only has one row or instance in an array.
I know its advantageous to use them for multiple rows which could be missed if you used a for loop.
But do I really need to use it just to echo one variable thats in an array?
e.g. for example this variable $stats
array(3) { ["user_interventions"]=> int(4) ["fastest_intervention"]=> array(1) { [0]=> object(stdClass)#22 (1) { ["duration"]=> string(8) "02:10:00" } } ["slowest_intervention"]=> array(1) { [0]=> object(stdClass)#23 (1) { ["duration"]=> string(8) "02:26:00" } } }
Thanks
if you know the 'address' of the value in your array, then there's no need for a loop:
echo $arr['user_interventions'][0]['duration']; // 02:10:00
More details here.
No, you do not need to use a foreach loop every time you need to access an array value. Your example could be used in the following manner...
echo $stats['fastest_intervention']['0']->duration; // Outputs: 02:10:00
Here's your variable dump with indentation (makes it easier to read).
array(3) {
["user_interventions"]=> int(4)
["fastest_intervention"]=> array(1) {
[0]=> object(stdClass)#22 (1) {
["duration"]=> string(8) "02:10:00"
}
}
["slowest_intervention"]=> array(1) {
[0]=> object(stdClass)#23 (1) {
["duration"]=> string(8) "02:26:00"
}
}
}
You need not to use foreach here but you can't just print $array
if you indexes of array you may print something like:
print 'Key is '.$array['key'].' but index is only'.$array['index'];
You just access the variables using []. print $array['key']