Retrieve value from SimpleXML object in PHP - php

$bbb = new BigBlueButton();
$recordingsParams = array(
'meetingId' => '',
);
// Now get recordings info and display it:
$itsAllGood = true;
try {$result = $bbb->getRecordingsWithXmlResponseArray($recordingsParams);}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
$itsAllGood = false;
}
if ($itsAllGood == true) {
if ($result == null) {
echo "Failed to get any response. Maybe we can't contact the BBB server.";
}
else {
if ($result['returncode'] == 'SUCCESS') {
echo "<p>Meeting info was found on the server.</p>";
}
else {
echo "<p>Failed to get meeting info.</p>";
}
print_r($result);
}
}
When I am using Bigbluebutton, I need to retrieve the particular data from these XML format response. I don't know how to retrieve the particular data from these XML format?
Array
(
[returncode] => SimpleXMLElement Object
(
[0] => SUCCESS
)
[0] => Array
(
[meetingId] => SimpleXMLElement Object
(
[0] => newtech
)
)
[1] => Array
(
[meetingId] => SimpleXMLElement Object
(
[0] => menew
)
)
)
I need to display the values of meetingId.

If you'd rather work with arrays you can cast the XML as well. This function returns an array with info on what is going on on your server if called (improvements still very welcome):
function getServerInfo() {
$url="https://you-bbb-server-api-getMeetings-call-url";
$a= (array)new SimpleXMLElement(file_get_contents($url));
if($a["returncode"]=="SUCCESS") {
if($a["meetings"]) {
foreach($a["meetings"] as $meeting) {
$meeting=(array)$meeting;
$data["Meetings"][$meeting["meetingID"]]["Teilnehmer"]=$meeting["participantCount"];
$data["Meetings"][$meeting["meetingID"]]["Name"]=$meeting["meetingName"];
$data["Gesamt"]+=(int)$meeting["participantCount"];
$data["Anzahl"]++;
$data["Meetings"][$meeting["meetingID"]]["Video"]=$meeting["videoCount"];
$data["Meetings"][$meeting["meetingID"]]["Start"]=date('d.m.Y H:i:s',floor($meeting["startTime"]/1000));
if($meeting["attendees"]) foreach($meeting["attendees"] as $att) {
$att=(array)$att;
if($att["role"]=="MODERATOR") $data["Meetings"][$meeting["meetingID"]]["Liste"]["M"]=array($att["fullName"],($att["hasJoinedVoice"]=="true")? 1:0,($att["hasVideo"]=="true")? 1:0);
else $data["Meetings"][$meeting["meetingID"]]["Liste"]["T"][]=array($att["fullName"],($att["hasJoinedVoice"]=="true")? 1:0,($att["hasVideo"]=="true")? 1:0);
}
}
return($data);
} else return(array("Anzahl"=>0,"Gesamt"=>0));
} else return(-1);
}

Related

error while appending data into an array using array_push in php

I want to filter my data_array and create a new array $arr with new data.I tried using following function.it is not appending data. but it is replacing the data.I know that I have to use array_push(). when I did that data is appending to the array as single elements.
foreach ($data_array as $value) {
try {
$rep = $value->rep;
$idposition_rep = $value->idposition_rep;
$max_idinvoice = $value->max_idinvoice;
$idsession = $value->idsession;
$i_date = $value->i_date;
$last_i_time_string = $value->last_i_time;
$delayTime = $value->delayTime;
if ($delayTime > 30) {
$arr[] = array(
'rep' => $rep,
'idposition_rep' => $idposition_rep,
'max_idinvoice' => $max_idinvoice,
'idsession' => $idsession,
'i_date' => $i_date,
'last_i_time_string' => $last_i_time_string,
'curr_time' => date("H:i:s"),
'delayTime' => $delayTime);
}
} catch (PDOException $ex) {
echo $ex->getMessage();
die;
}
}
I had created sample code based on your requirement. replace as per your requirement with variables and assignment.
$data_array is sample input array.
$data_array = array('1' => 'abc', '2'=>'das', '3' => 'def');
$arr = array();
$i=0;
foreach ($data_array as $value) {
try {
$rep = $value;
$aval = strpos($rep,'a'); // Put Your condition for display Time > 30
if ($aval !== false) {
$arr[$i] = array(
'rep' => $rep // assign values get from input array.
);
$i++;
}
} catch (PDOException $ex) {
echo $ex->getMessage();
die;
} }
print_r($arr);
OUTPUT:
Array
(
[0] => Array
(
[rep] => abc
)
[1] => Array
(
[rep] => das
)
)
Hope this will help you.

how to filter php array list and get return as array

this is my array in print_r()
Array([0]=> stdCLass Object ([name] =>john
[surname] =>future
[group] =>one1
)
[1]=> stdCLass Object ([name] =>chris
[surname] =>past
[group] =>two2
)
)
what I want to do is search this array by group. example. tell it
group ="one1"
and my return would be name=john , surname = future
I don't know how to attempt this.
Assuming the array is called $groups
To return an array containing the name and surname
function get_name_from_groups($groups, $group_name)
{
foreach ( $groups as $group ) {
if ( $group->group == $group_name ) {
return array( 'name' => $group->name,
'surname' => $group->surname
);
}
}
return false;
}
$var = get_name_from_groups($groups, 'one1');
if ( $var === false ) {
echo 'The group one1 does not exist';
exit;
}
echo 'Name = ' . $var['name'];
echo 'Surname = ' . $var['surname'];
To return an object containing the name and surname
function get_name_from_groups($groups, $group_name)
{
foreach ( $groups as $group ) {
if ( $group->group == $group_name ) {
$ret = new stdClass();
$ret->name = $group->name;
$ret->surname = $group->surname;
}
}
return false;
}
$var = get_name_from_groups($groups, 'one1');
if ( $var === false ) {
echo 'The group one1 does not exist';
exit;
}
echo 'Name = ' . $var->name;
echo 'Surname = ' . $var->surname;

How can i add element to my array under a specific key?

How can i add element to my array under a specific key?
This is my array output before i use foreach. As you can see, the error field is empty. I want to fill it out.
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] =>
)
This is my foreach. As you can see i already tried to make this work by implementing $arrayname['index'] = $value;. But this does not work, nothing comes out when i spit out in a print_r. Why is this happening?
foreach ($samlet as $key)
{
if ($key['pricebefordiscount'] > '200000')
{
$samlet['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$samlet['error'] = "Testscan";
}
}
This is the desired output:
Array (
[0] => Array (
[transactionid] => 2223
[created] => 26-02-13 14:07:00
[cardid] => 10102609
[pricebefordiscount] => 68900
[error] => "Testscan"
)
Change your foreach, so you have the indexes used in the "main" $samlet array:
foreach($samlet as $key => $array)
{
if ($array['cardid'] === '88888888')
{
$samlet[$key]['error'] = '0/2000';
}
}
And so on...
Try this :
foreach ($samlet as &$key){
if ($key['pricebefordiscount'] > '200000'){
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888'){
$key['error'] = "Testscan";
}
}
According to PHP manual:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
So your code should looke like this:
<?php
foreach ($samlet as &$key)
{
if ($key['pricebefordiscount'] > '200000')
{
$key['error'] = "O/2000";
}
if ($key['cardid'] === '88888888')
{
$key['error'] = "Testscan";
}
}
TRY THIS
foreach ($samlet as $key=>$value)
{
if ($value['pricebefordiscount'] > '200000')
{
$samlet[$key]['error'] = "O/2000";
}
if ($value['cardid'] === '88888888')
{
$samlet[$key]['error'] = "Testscan";
}
}

Return true/false on searching multidimensional array

I have the following multidimensional $array:
Array
(
[0] => Array
(
[domain] => example.tld
[type] => 2
)
[1] => Array
(
[domain] => other.tld
[type] => 2
)
[2] => Array
(
[domain] => blaah.tld
[type] => 2
)
)
I simply want to recursively search all the arrays on both key and value, and return true if the key/value was found or false if nothing was found.
Expected output:
search_multi_array($array, 'domain', 'other.tld'); // Will return true
search_multi_array($array, 'type', 'other.tld'); // Will return false
search_multi_array($array, 'domain', 'google.com'); // Will return false
I've figured out a ugly-ugly method to search against the domain against all keys with this function:
function search_multi_array($search_value, $the_array) {
if (is_array($the_array)) {
foreach ($the_array as $key => $value) {
$result = search_multi_array($search_value, $value);
if (is_array($result)) {
return true;
} elseif ($result == true) {
$return[] = $key;
return $return;
}
}
return false;
} else {
if ($search_value == $the_array) {
return true;
}
else
return false;
}
}
Can anyone do better and match both against the key and value in a more elegant way?
If it doesn't go beyond those 2 levels, flipping keys/merging makes life a lot more pleasant:
<?php
$data = array
(
'0' => array
(
'domain' => 'example.tld',
'type' => 2
),
'1' => array
(
'domain' => 'other.tld',
'type' => 2,
),
'2' => array
(
'domain' => 'blaah.tld',
'type' => 2
)
);
$altered = call_user_func_array('array_merge_recursive',$data);
var_dump($altered);
var_dump(in_array('other.tld',$altered['domain']));
var_dump(in_array('other.tld',$altered['type']));
var_dump(in_array('google.com',$altered['domain']));
To go beyond 2nd level, we have to loop once through all the nodes:
$option2 = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $key => $value){
$option2[$key][] = $value;
}
var_dump($option2);
One way is to create a reverse mapping from [domain] => [indices] and from [type] => [indices]. It's probably not going to save you much unless you do lots of searches.
(hint: you probably want to wrap it into a class to prevent inconsistencies in the mappings)
also, anytime you see something like this:
if ($search_value == $the_array) {
return true;
} else {
return false;
}
you can always turn it into:
return $search_value == $the_array;
function search_mutli_array($SearchKey, $SearchValue, $Haystack)
{
$Result = false;
if (is_array($Haystack))
{
foreach ($Haystack as $Key => $Value)
{
if (is_array($Value))
{
if (search_mutli_array($SearchKey, $SearchValue, $Value))
{
$Result = true;
break;
}
}
else if ($SearchKey == $Key && $SearchValue == $Value)
{
$Result = true;
break;
}
}
}
return $Result;
}

Extract leaf nodes of multi-dimensional array in PHP

Suppose I have an array in PHP that looks like this
array
(
array(0)
(
array(0)
(
.
.
.
)
.
.
array(10)
(
..
)
)
.
.
.
array(n)
(
array(0)
(
)
)
)
And I need all the leaf elements of this mulit-dimensional array into a linear array, how should I go about doing this without resorting recursion, such like this?
function getChild($element)
{
foreach($element as $e)
{
if (is_array($e)
{
getChild($e);
}
}
}
Note: code snippet above, horribly incompleted
Update: example of array
Array
(
[0] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 5000000
[balance:private] => 4998970
[queueid:private] => 0
[sellerid:private] => 2
[dateTime:private] => 2009-07-25 17:53:10
)
)
)
...snipped.
[2] => Array
(
[0] => Array
(
[0] => Seller Object
(
[credits:private] => 10000000
[balance:private] => 9997940
[queueid:private] => 135
[sellerid:private] => 234
[dateTime:private] => 2009-07-14 23:36:00
)
)
....snipped....
)
)
Actually, there is a single function that will do the trick, check the manual page at: http://php.net/manual/en/function.array-walk-recursive.php
Quick snippet adapted from the page:
$data = array('test' => array('deeper' => array('last' => 'foo'), 'bar'), 'baz');
var_dump($data);
function printValue($value, $key, $userData)
{
//echo "$value\n";
$userData[] = $value;
}
$result = new ArrayObject();
array_walk_recursive($data, 'printValue', $result);
var_dump($result);
You could use iterators, for example:
$result = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::LEAVES_ONLY) as $value) {
$result[] = $value;
}
Use a stack:
<?php
$data = array(array(array("foo"),"bar"),"baz");
$results = array();
$process = $data;
while (count($process) > 0) {
$current = array_pop($process);
if (is_array($current)) {
// Using a loop for clarity. You could use array_merge() here.
foreach ($current as $item) {
// As an optimization you could add "flat" items directly to the results array here.
array_push($process, $item);
}
} else {
array_push($results, $current);
}
}
print_r($results);
Output:
Array
(
[0] => baz
[1] => bar
[2] => foo
)
This should be more memory efficient than the recursive approach. Despite the fact that we do a lot of array manipulation here, PHP has copy-on-write semantics so the actual zvals of the real data won't be duplicated in memory.
Try this:
function getLeafs($element) {
$leafs = array();
foreach ($element as $e) {
if (is_array($e)) {
$leafs = array_merge($leafs, getLeafs($e));
} else {
$leafs[] = $e;
}
}
return $leafs;
}
Edit   Apparently you don’t want a recursive solution. So here’s an iterative solution that uses a stack:
function getLeafs($element) {
$stack = array($element);
$leafs = array();
while ($item = array_pop($stack)) {
while ($e = array_shift($item)) {
if (is_array($e)) {
array_push($stack, array($item));
array_push($stack, $e);
break;
} else {
$leafs[] = $e;
}
}
}
return $leafs;
}
Just got the same issue and used another method that was not mentioned. The accepted answer require the ArrayObject class to work properly. It can be done with the array primitive and the use keyword in the anonymous function (PHP >= 5.3):
<?php
$data = array(
array(1,2,3,4,5),
array(6,7,8,9,0),
);
$result = array();
array_walk_recursive($data, function($v) use (&$result) { # by reference
$result[] = $v;
});
var_dump($result);
There is no flatten function to get directly the leafs. You have to use recursion to check for each array if has more array children and only when you get to the bottom to move the element to a result flat array.

Categories