(PHP) Generic code to get different structure of arrays (objects) - php

I have 2 structures of arrays (objects) returned :
1) If only 1 data returned :
stdClass Object
(
[result] => stdClass Object
(
[recordData] => stdClass Object
(
[fieldNames] => Array
(
[0] => CUSTOMER_ID_
[1] => EMAIL_ADDRESS_
[2] => FIRST_NAME
[3] => LAST_NAME
[4] => SEX
[5] => DATE_OF_BIRTH
)
**[records] => stdClass Object
(
[fieldValues] => Array
(
[0] => CUSTOMER_ID_001
[1] => email001#test.com
[2] => FIRST_NAME_001
[3] => LAST_NAME_001
[4] => M
[5] => 01/01/1991
)
)**
)
)
)
2) If more than 1 data returned :
stdClass Object
(
[result] => stdClass Object
(
[recordData] => stdClass Object
(
[fieldNames] => Array
(
[0] => CUSTOMER_ID_
[1] => EMAIL_ADDRESS_
[2] => FIRST_NAME
[3] => LAST_NAME
[4] => SEX
[5] => DATE_OF_BIRTH
)
**[records] => Array
(
[0] => stdClass Object
(
[fieldValues] => Array
(
[0] => CUSTOMER_ID_001
[1] => email001#test.com
[2] => FIRST_NAME_001
[3] => LAST_NAME_001
[4] => M
[5] => 01/01/1991
)
)
[1] => stdClass Object
(
[fieldValues] => Array
(
[0] => CUSTOMER_ID_002
[1] => email002#test.com
[2] => FIRST_NAME_002
[3] => LAST_NAME_002
[4] => F
[5] => 02/02/1992
)
)
)**
)
)
)
Currently i am using this code :
foreach ($memberlist->result->recordData->records as $list)
{
$out .= "<tr>";
foreach ($list as $memberarray)
{
foreach ($memberarray as $member)
{
$out .= "<td>" . $member . "</td>";
}
}
$out .= "</tr>";
}
but it does not work when only 1 data returned.
How can I modify my code to get both structures?
Thank You.

I believe this should do the trick:
// If it is already an array, leave it as an array, if it's not, place it in an array
$member_records = ( is_array( $memberlist->result->recordData->records ) ? $memberlist->result->recordData->records : array( $memberlist->result->recordData->records ) );
foreach ($member_records as $list)
{
$out .= "<tr>";
foreach ($list as $memberarray)
{
foreach ($memberarray as $member)
{
$out .= "<td>" . $member . "</td>";
}
}
$out .= "</tr>";
}

Related

Combine some php sub-arrays, with condition

$routes array:
[admin/login] => Array
(
[0] => POST|AJAX
[1] => admin/login
[2] => admin/login
)
[admin/logout] => Array
(
[0] => POST
[1] => admin/logout
[2] => admin/logout
)
[admin/dashboard] => Array
(
[0] => GET
[1] => admin/dashboard
[2] => admin/dashboard
)
[admin/products] => Array
(
[0] => GET
[1] => admin/products/[:pag]
[2] => admin/products/all
)
[admin/products/add] => Array
(
[0] => GET
[1] => admin/product/add
[2] => admin/products/add
)
[admin/products/insert] => Array
(
[0] => POST
[1] => admin/product/insert
[2] => admin/products/insert
)
[admin/products/show] => Array
(
[0] => GET
[1] => admin/product/[i:id]
[2] => admin/products/show
)
[admin/products/edit] => Array
(
[0] => GET
[1] => admin/product/[i:id]/edit
[2] => admin/products/edit
)
[admin/products/update] => Array
(
[0] => POST
[1] => admin/product/update
[2] => admin/products/update
)
[admin/products/delete] => Array
(
[0] => POST
[1] => admin/product/delete
[2] => admin/products/delete
)
[admin/categories] => Array
(
[0] => GET
[1] => admin/categories
[2] => admin/categories/all
)
[admin/categories/add] => Array
(
[0] => GET
[1] => admin/category/add
[2] => admin/categories/add
)
[admin/categories/insert] => Array
(
[0] => POST
[1] => admin/category/insert
[2] => admin/categories/insert
)
[admin/categories/show] => Array
(
[0] => GET
[1] => admin/category/[i:id]
[2] => admin/categories/show
)
[admin/categories/edit] => Array
(
[0] => GET
[1] => admin/category/[i:id]/edit
[2] => admin/categories/edit
)
[admin/categories/update] => Array
(
[0] => POST
[1] => admin/category/update
[2] => admin/categories/update
)
[admin/categories/delete] => Array
(
[0] => POST
[1] => admin/category/delete
[2] => admin/categories/delete
)
[admin/api] => Array
(
[0] => GET
[1] => admin/api
[2] => admin/api/all
)
[admin/filter/sessions] => Array
(
[0] => POST|AJAX
[1] => admin/filter/sessions
[2] => admin/filters/sessions
)
This is $admin_routes array (build from $routes):
[login] => Array
(
[0] => admin/login
)
[logout] => Array
(
[0] => admin/logout
)
[dashboard] => Array
(
[0] => admin/dashboard
)
[products] => Array
(
[0] => admin/products
[1] => admin/products/add
[2] => admin/products/insert
[3] => admin/products/show
[4] => admin/products/edit
[5] => admin/products/update
[6] => admin/products/delete
)
[api] => Array
(
[0] => admin/api
)
[filter] => Array
(
[0] => admin/filter/sessions
)
[categories] => Array
(
[0] => admin/categories
[1] => admin/categories/add
[2] => admin/categories/insert
[3] => admin/categories/show
[4] => admin/categories/edit
[5] => admin/categories/update
[6] => admin/categories/delete
)
I need some help from you guys about $admin_routes.
I want to combine all sub-arrays from $admin_routes, from same area, which has only one element, in a new sub-array with key name formed from their key names.
Also i want the new sub-array to have same 'position' in line.
My imperfect solution:
// creating $admin_routes
$admin_routes = [];
foreach ($routes as $name => $route) {
if (preg_match('/^admin\/(.*)$/', $name))
$admin_routes[explode('/', $name)[1]][] = $name;
}
// imperfect solution for what i want
$single = false;
$waiting = [];
foreach ($admin_routes as $section => $routes) {
if (count($routes) == 1) { // remember all sub-arrays, with one single element, from same area
$single = true;
$waiting[$section] = $routes;
}
else if ($single) { // if found all sub-arrays, with one single element, from same area
$name = '';
$subarray = [];
foreach ($waiting as $section => $routes) {
// creating only one sub-array
$name .= ($section . ' ');
$subarray = array_merge($subarray, $routes);
unset($admin_routes[$section]);
}
// the problem is, sub-array it's added at the end of $admin_routes
// (not where sub-array's elements were before)
$admin_routes[$name] = $subarray;
$single = false;
$waiting = [];
}
}
The problem is, the new sub-arrays are placed at the end.
If you have any idea, please help me. Thx.
Using your actual result $admin_routes, you could loop through them and rebuild the desired array:
$real_routes = []; // The new array
$singles_key = ''; // The key for combined sub-arrays
$singles_routes = []; // The routes for combined sub-arrays
foreach ($admin_routes as $name => $r) {
/* If this route array has a single entry,
add its name and value to our temp vars */
if (count($r) === 1) {
$singles_key .= $name . ' ';
$singles_routes = array_merge($singles_routes, $r);
} else {
/* If then a route array has multiple value,
save the combined singles and then save this one */
if (!empty($singles_key)) {
$real_routes[trim($singles_key)] = $singles_routes;
$singles_key = '';
$singles_routes = [];
}
$real_routes[$name] = $r;
}
}
/* If the loop ends but the temp vars aren't empty,
save the lasts combined singles */
if (!empty($singles_key)) {
$real_routes[trim($singles_key)] = $singles_routes;
}
// Then to output:
echo '<pre>' . print_r($real_routes, true) . '</pre>';

How can I access multi-dimensional array with php?

My array is like this. So how can I access the names,values with php?
Array(
[0] => Array
(
[name] => subject
[value] => คอมพิวเตอร์ ม.3
)
[1] => Array
(
[name] => subject_code
[value] => ง33101
)
[2] => Array
(
[name] => subject_hour
[value] => 2
)
[3] => Array
(
[name] => semester
[value] => 1
)
[4] => Array
(
[name] => level
[value] => 3
)
[5] => Array
(
[name] => classroom
[value] => 301
)
[6] => Array
(
[name] => classroom
[value] => 302
)
)
I have tried FOREACH to loop through the array and it does the job, but how can I get their names and values to be used later?
My FOREACH code:
foreach($objects AS $values){
foreach($values as $value){
echo $value.'<br/>';
}
}
assume your array is $array:
foreach($array as $item){
$name = $item['name']; //extract name
$value = $item['value']; //extract value
echo $name.' '.$value.'</br>';
}
To get the index/key, just name it:
foreach($collection as $key => $value)
print($key . ' = ' . $value . '\n');
Iteration over $objects to get values and names;
foreach($objects as $value){
echo "Name: ".$value['name'];
echo " - Value: ".$value['value'];
echo "<br/>";
}

Read array-node with foreach, doesn't work

I have this array in a foreach-loop with the 'as' $train
Now i want to read out the 'mat'-node.
I've tried this:
<?php
echo "<!-- ";
foreach ($train['mat'] as $mat) {
echo "Mat:" . $mat . "";
}
echo " -->";
?>
But it gives a empty foreach result in mijn HTML-source, between the comments.
Array
(
[status] => 0
[via] => Utrecht C., Houten, Geldermalsen
[bestemming] => Tiel
[vleugels] => Array
(
[0] => Array
(
[stopstations] => Array
(
[0] => Array
(
[naam] => Vleuten
[code] => VTN
)
[1] => Array
(
[naam] => Utrecht Terwijde
[code] => UTT
)
[2] => Array
(
[naam] => Utrecht Leidsche Rijn
[code] => UTLR
)
)
[bestemming] => Tiel
[mat] => Array
(
[0] => Array
(
[0] => SLT-4
[1] => Tiel
[2] => 2422
)
[1] => Array
(
[0] => SLT-4
[1] => Tiel
[2] => 2464
)
)
)
)
[vervoerder] => NS
[spoor] => 6
)
Hope this help.
But I think you need read more about PHP Array and Array index
echo "<!-- ";
foreach($train['vleugels'][0]['mat'] as $mat) {
echo "Mat:".$mat[2]."<br>";
}
echo " -->";
// <!-- 2422 2464 -->

Ranking array base on key php

I have an array of object "$arr" like this:
Array
(
[0] => stdClass Object
(
[1] => 1
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 2
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
What I want to do is rank the value based on the key. If key($arr[$idx+1]) < key($arr[$idx]) then increase value of $arr[idx] by 1. So the results would look like:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 5
)
[3] => stdClass Object
(
[3] => 4
)
[4] => stdClass Object
(
[2] => 3
)
)
this is what I have done so far:
$arrIdx2=[];
foreach($arrIdx as $key=>$value){
$newVal = new stdClass();
$newVal->$key = $value;
$arrIdx2[] = $newVal;
}
foreach($arrIdx2 as $key=>$value){
$i= key((array)$value);
$m = $value->$i; //get the first value
for($j = $key+1; $j< $len; $j++){
$i2 = key((array)$arrIdx2[$j]); //get the key of second value
$n = $arrIdx2[$j]->$i2;
if($n == $m){
if($i2 < $i){
$arrIdx2[$key]->$i += 1;
}
}
}
}
and this is the result I got:
Array
(
[0] => stdClass Object
(
[1] => 2
)
[1] => stdClass Object
(
[0] => 1
)
[2] => stdClass Object
(
[4] => 3
)
[3] => stdClass Object
(
[3] => 2
)
[4] => stdClass Object
(
[2] => 3
)
)
What's the best way to do this? Can anyone guide me? Thanks
Do this with associative array. I can't make an object array
right now. If you provide me the object array then i will update my answer.
Try this:
$arr = array(
array("1" => 1),
array("0" => 1),
array("4" => 2),
array("3" => 2),
array("2" => 3)
);
$out = array();
$first = key(current($arr));
$end = key(end($arr));
foreach($arr as $key => $val){
$comp = (key($val) == $end) ? $end : key($arr[$key+1]);
if($comp <= key($val))
$out[$key][key($val)] = key($val) + 1;
else
$out[$key][key($val)] = $val[key($val)];
}
echo '<pre>';
print_r($out);
Result
Array
(
[0] => Array
(
[1] => 2
)
[1] => Array
(
[0] => 1
)
[2] => Array
(
[4] => 5
)
[3] => Array
(
[3] => 4
)
[4] => Array
(
[2] => 3
)
)
I think you want this, let me know.

Getting data from SimpleDB using PHP

How do I get data out of SimpleDB? All I wanted to do was put data in and then get data out. It looks like the data is not easy to get out and in the end will require computing power to extract by looping etc. Am I correct?
Here is my code to extract the data:
<?php
// Include the SDK
require_once 'sdk.class.php';
// Instantiate
$sdb = new AmazonSDB();
$select_expression = 'SELECT * FROM ' . $domain_name;
$next_token = null;
do {
if ($next_token) {
$response = $sdb->select($select_expression, array(
'NextToken' => $next_token,
));
} else {
$response = $sdb->select($select_expression);
}
// Get Data for row
$body = $response->body->to_array()->getArrayCopy();
echo "ID: " . $msgId . "<br>";
$next_token = isset($response->body->SelectResult->NextToken)
? (string) $response->body->SelectResult->NextToken
: null;
}
while ($next_token);
echo "<br>";
?>
Here is the extract of the data I'm trying to extract.
Array
(
[#attributes] => Array
(
[ns] => http://sdb.amazonaws.com/doc/2009-04-15/
)
[SelectResult] => Array
(
[Item] => Array
(
[0] => Array
(
[Name] => 1
[Attribute] => Array
(
[0] => Array
(
[Name] => msgAddress
[Value] => +2782555555
)
[1] => Array
(
[Name] => msgType
[Value] => S
)
[2] => Array
(
[Name] => msgSubmitDate
[Value] => 2012-09-02 15:48:46
)
[3] => Array
(
[Name] => msgText
[Value] => Test SMS message for ID no 1
)
)
)
[1] => Array
(
[Name] => 2
[Attribute] => Array
(
[0] => Array
(
[Name] => msgAddress
[Value] => +27825555555
)
[1] => Array
(
[Name] => msgType
[Value] => P
)
[2] => Array
(
[Name] => msgSubmitDate
[Value] => 2012-09-02 15:48:46
)
[3] => Array
(
[Name] => msgText
[Value] => Test phone message for ID no 2
)
)
)
[2] => Array
(
[Name] => 3
[Attribute] => Array
(
[0] => Array
(
[Name] => msgAddress
[Value] => name#domain.co.za
)
[1] => Array
(
[Name] => msgType
[Value] => E
)
[2] => Array
(
[Name] => msgSubmitDate
[Value] => 2012-09-02 15:48:46
)
[3] => Array
(
[Name] => msgText
[Value] => Test email message for ID no 3 to name#domain.co.za
)
)
)
[3] => Array
(
[Name] => 4
[Attribute] => Array
(
[0] => Array
(
[Name] => msgAddress
[Value] => andrebruton
)
[1] => Array
(
[Name] => msgType
[Value] => P
)
[2] => Array
(
[Name] => msgSubmitDate
[Value] => 2012-09-02 15:48:46
)
[3] => Array
(
[Name] => msgText
[Value] => Test push notification message for ID no 4
)
)
)
)
)
)
All I want to get is the following variables:
msgId (the Name), msgType, msgAddress, msgText, msgSubmitDate
If I can get it using $msgType = Body->SelectResult->Item->Name or something like that.
Using XPath is going to perform about 100x faster. I haven't tested this code, but the XPath expression should be pretty close:
$msgAddress = (string) $response->body->query('//Attribute[Name[text()="msgAddress"]]/Value')->first();
I figured it out using some old Tarzan code. This works for a 2 dimensional array (data similar to a standard database)
Here is the working code:
<?php
// Include the SDK
require_once 'sdk.class.php';
// Instantiate
$sdb = new AmazonSDB();
$select_expression = 'SELECT * FROM ' . $domain_name;
$next_token = null;
do {
if ($next_token) {
$response = $sdb->select($select_expression, array(
'NextToken' => $next_token,
));
} else {
$response = $sdb->select($select_expression);
}
// Get Data for row
foreach ($response->body->SelectResult->Item as $item)
{
$msgId = $item->Name;
foreach ($item->Attribute as $attr)
{
if ($attr->Name == 'msgAddress') {
$msgAddress = $attr->Value;
}
if ($attr->Name == 'msgType') {
$msgType = $attr->Value;
}
if ($attr->Name == 'msgSubmitDate') {
$msgSubmitDate = $attr->Value;
}
if ($attr->Name == 'msgText') {
$msgText = $attr->Value;
}
}
echo "<br>msgId: $msgId<br>";
echo "msgAddress: $msgAddress<br>";
echo "msgType: $msgType<br>";
echo "msgSubmitDate: $msgSubmitDate<br>";
echo "msgText: $msgText<br><br>";
}
$next_token = isset($response->body->SelectResult->NextToken)
? (string) $response->body->SelectResult->NextToken
: null;
}
while ($next_token);
echo "<br>";
?>
$body = $response->body->to_array()->getArrayCopy();
echo "ID: " . $msgId . "<br>";
//but $msgId is not set

Categories