Access Multi dimensional array through a dynamic variable - php

I am trying to pass a dynamic variable into a multidimensional array.
This is the actual code:
for($i = 0; $i < count($social ["#object"] -> field_sector ["und"]); $i++){
echo $social ["#object"] -> field_sector ["und"] [$i] ["taxonomy_term"] -> name;
}
Since I want to re-use this code for multiple types, I created a function
function render_multi_array ($parent, $field_name) {
for($i = 0; $i < count($parent ["#object"] -> $field_name ["und"]); $i++){
echo $parent ["#object"] -> $field_name ["und"] [$i] ["taxonomy_term"] -> name;
}
}
The issue is happening with $field_name as I am unable to provide this dynamically. Any idea how I can make this function work?
Sample array is follows:
Array
(
[#title] => Sector
[#field_name] => field_sector
[#object] => stdClass Object
(
[vid] => 1079
[uid] => 30
[vuuid] => 83ab0817-0175-4541-b20e-93611c20c026
[nid] => 1077
[type] => random_study
[field_random_id] => Array
(
[und] => Array
(
[0] => Array
(
[value] => CS_525
[format] =>
[safe_value] => CS_525
)
)
)
[field_sector] => Array
(
[und] => Array
(
[0] => Array
(
[tid] => 411
[taxonomy_term] => stdClass Object
(
[tid] => 411
[vid] => 10
[name] => Sample title goes here.
)
)
[1] => Array
(
[tid] => 248
[taxonomy_term] => stdClass Object
(
[tid] => 248
[vid] => 10
[name] => Energy
)
)
)
)

In PHP 7 the code should work as written. PHP 7.0 changed evaluation order to strictly left to right.
In PHP 5, you'll get an illegal string offset warning because PHP is trying to first evaluate $field_name["und"] (e.g. "field_sector"["und"]) and use the result of that as the property name in #object rather than evaluating $parent["#object"]->$field_name to get the array and then accessing that with ["und"].
You can prevent that by bracketing the variable like this:
function render_multi_array ($parent, $field_name) {
for ($i = 0; $i < count($parent["#object"]->{$field_name}["und"]); $i++){
echo $parent ["#object"]->{$field_name}["und"][$i]["taxonomy_term"]->name;
}
}
Adding those brackets won't cause any problems if you upgrade to PHP 7 later.
By the way, it looks like this code would be simpler with a foreach loop instead.
function render_multi_array ($parent, $field_name) {
foreach ($parent['#object']->{$field_name}['und'] as $item) {
echo $item['taxonomy_term']->name;
}
}

Related

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

Cycling an array and delete item

I need help :)
I've to code a script that, cycling through an array inside an array , delete an element if in XXX field there isn't value (is NULL ).
My array is:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[0] => stdClass Object ( [name] => minnie [email] => blabla#gmail.com [XXX] => )
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
In this example the item [0] has no value in XXX value so my output array will be:
Array (
[idCampaign] => 3
[idIT] => 322
[recipients] =>Array (
[1] => stdClass Object ( [name] => [email] => fddd#gmail.it [XXX] => 0.88451100 )
) ) [date] => MongoDate Object ( [sec] => 1468503103 [usec] => 0 ) )
i hope that you can help me :)
You could use a nested foreach() Loop to cycle through the Data and then perform some tests, which on failing, guarantees that it is safe to unset the pertinent variable. Here's how:
<?php
// WE SIMULATE SOME DATA TO POPULATE THE ARRAY, ONLY FOR TESTING PURPOSES
$objDate = new stdClass();
$objRez1 = new stdClass();
$objRez2 = new stdClass();
$objRez1->name = "minnie";
$objRez1->email = "blabla#gmail.com";
$objRez1->XXX = null;
$objRez2->name = null;
$objRez2->email = "fddd#gmail.it";
$objRez2->XXX = 0.88451100;
$objDate->sec = 1468503103;
$objDate->usec = 0;
// IN THE END WE NOW HAVE A SAMPLE ARRAY (SIMULATED) TO WORK WITH.
$arrData = array(
'idCampaign' => 3,
'idIT' => 322,
'recipients' => array(
$objRez1,
$objRez2
),
'date' =>$objDate,
);
// LOOP THROUGH THE ARRAY OF DATA THAT YOU HAVE
// NOTICE THE &$data IN THE LOOP CONSTRUCT...
// THIS IS NECESSARY FOR REFERENCING WHEN WE UNSET VARIABLES WITHIN THE LOOP
foreach($arrData as $key=>&$data){
// SINCE THE XXX KEY IS STORED IN THE 'recipients' ARRAY,
// WE CHECK IF THE CURRENT KEY IS 'recipients' & THAT $data IS AN ARRAY
if($key == "recipients" && is_array($data)){
// NOW WE LOOP THROUGH THE DATA WHEREIN THE 'XXX' KEY LIVES
foreach($data as $obj){
// IF THE VALUE OF THE XXX KEY IS NULL OR NOT SET,
// WE SIMPLY UNSET IT...
if(!$obj->XXX){
unset($obj->XXX);
}
}
}
}
var_dump($arrData);
You can verify the Results HERE.
Hope this could offer you a little tip on how to implement it rightly on your own...
This should do the job
foreach($arrayOfObjects as $index => $object){
if(!isset($object->xxx) || empty($object->xxx)){
unset($arrayOfObjects[$index]);
}
}

php removing an element from objects

So, I have following db result:
Array
(
[0] => stdClass Object
(
[id] => 1
[user] => 1
[img] => 2016/02/img_8488.jpg
[url] => /p=?44
[sent_date] => 2016-02-13 00:00:00
)
[1] => stdClass Object
(
[id] => 2
[user] => 185
[img] =>
[url] => /?p=54
[sent_date] => 2016-02-06 00:00:00
)
)
How would I remove [id] and [sent_date] from the query result?
I am not sure if I am using unset right.
unset($results[0]['id']);
$reindex = array_values($results);
$objectarray = $reindex;
Instead of removal or unset you can create a new array;
$i = 0;
$newResult = array();
foreach($result as $value){
$newResult[$i]["user"] = $value->user;
$newResult[$i]["img"] = $value->img;
$newResult[$i]["url"] = $value->url;
$i++;
}
print_r($newResult);
$newResult will return the new array and your original array remains same you can use it if you need.
Or removal of indexes is must required than use unset inside the foreach loop as:
unset($value->id);
unset($value->sent_date);
Side note:
Also keep in mind you can not use it as $value["id"] becuase its a property not an array index.
Use unset($results[0]->id); and unset($results[0]->sent_date) instead and it should work. If you want to do this in all of the array objects:
for($i = 0; $i<sizeof($results); $i++)
{
unset($results[$i]->id);
unset($results[$i]->sent_date);
}

Retrieving correct record from multidimentional array

I'm having a mental freeze moment. If I have an array in the following format:
$myData = Array
(
[0] => stdClass Object
(
[id] => 1
[busID] => 5
[type] => SMS
[number] => 5128888888
)
[1] => stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
[2] => stdClass Object
(
[id] => 4
[busID] => 5
[type] => APP
[number] => 5129999988
[verified] => 1
[default] => 0
)
)
And I only have an var for ID of the record, how do I retrieve the rest of the detail for that set.
$myID = 2;
// get number 5125555555 and it's type
echo $myData[][$myID]['number']; // ???
The way you have your data arranged your going to have to loop through your array to identify the object corresponding to $myID.
foreach($myData as $object) if($object->id == $myID) echo $object->number;
The alternative is to arrange your $myData as an associative array with the id field as the key. Then you could access it simply with $myData[$myID]->number.
Actually it's an array that contains StdClass objects , try looping over $myData and access each attribute :
foreach ( $myData as $data )
{
print_r($data->id);
// ...
}
You can avoid loop by using following logic:
<?php
$myID = 2;
$myData = json_decode(json_encode($myData),1); // Convert Object to Array
$id_arr = array_column($myData, 'id'); // Create an array with All Ids
$idx = array_search($myID, $id_arr);
if($idx !== false)
{
echo $myData[$idx]['type'] . ' -- ' . $myData[$idx]['number'];
}
?>
Working Demo
Note: array_column is supported from PHP 5.5.
For lower versions you can use this beautiful library https://github.com/ramsey/array_column/blob/master/src/array_column.php
You can create a custom function to achieve this, you need to pass the array and id whose details you want and the function will return the array with matching id, like below
function detailsById($myData,$id){
foreach($myData as $data){
if($data->id == $id){
return $data;
}
}
}
Just call this function with your array and id..
$data=detailsById($myData,2);
echo "<pre>";print_r($data);
This will give you :
stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
And further to print 'number' and 'type' use $data array
$data['type'];
$data['number'];

Adding iteration to an objects properties in PHP

This is likely to be very inelegant however this is my problem.
I have a returned array of objects like this..
Array (
[count_assessor0] => stdClass Object ( [assessor0] => 91 )
[count_assessor1] => stdClass Object ( [assessor1] => 3 )
[count_assessor2] => stdClass Object ( [assessor2] => 5 )
[count_assessor3] => stdClass Object ( [assessor3] => 24 )
[count_verifier0] => stdClass Object ( [verifier0] => 91 )
[count_verifier1] => stdClass Object ( [verifier1] => 3 )
[count_verifier2] => stdClass Object ( [verifier2] => 5 )
[count_verifier3] => stdClass Object ( [verifier3] => 24 )
)
Ok, so as you can see each array and property have a numerical suffix. What I want to do is use these suffixes in a foreach loop below however when it comes to adding $n to the objects property I get an error as it doesn't 'add' the suffix on to $role.
$options = array('Yes - Qualified', 'Yes - Not Qualified', 'No - Working Towards', 'No - Not Working Towards');
$roles = array('assessor' => $options, 'verifier' => $options, 'teaching_status' => $options, 'coaching_status' => $options);
$i = 0 ;
foreach($roles as $role => $options){
echo ucwords($role);
$n = 0 ;
foreach($options as $option) {
echo $option ;
echo $count["count_$role$i"]->$role$n;
$n++ ;
$i++ ;
endforeach ;
unset($n) ;
endforeach ;
If I have explained this well enough can anyone help?
Thanks!
I think You should make use of dynamic variable name creation, it is well described here:
Dynamic variable names in PHP
So in You code there should be something like that:
$property = ${$role.$n};
echo $count["count_$role$i"]->$property;

Categories