I have the following function which works fine.
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$result[$object->id] = $object->first_name . ' ' . $object->last_name;
}
return $result;
}
However, I would like to pass in an array to $items, and have that exploded, so that I dont have to specify first_name and last_name manually.
If $item was only a single value (and not an array), then it would be simple:
$result[$object->id] = $object->$item;
But I have no idea how to make this work if $items contains multiple values and I want to join them with a space. Something like, the following, but I need to get the $object in there
$items = array('first_name', 'last_name');
$result[$object->id] = implode(' ', $items);
Do I get you right that you`d like to use the strings in $item as property-names of $object?
function ($objects, $items = array())
{
$result = array();
foreach ($objects as $object) {
$valuesToAssign = array();
foreach ($items as $property) {
$valuesToAssign[] = $object->$property;
}
$result[$object->id] = implode(' ', $valuesToAssign);
}
return $result;
}
I have no idea to avoid the second foreach, but that gives you the desired result.
Not sure if I got you right, but how about this:
function foo($objects, $items = array()) {
$result = array();
$keys = array_flip($items);
foreach ($objects as $object) {
// Cast object to array, then omit all the stuff that is not in $items
$values = array_intersect_key((array) $object, $keys);
// Glue the pieces together
$result[$object->id] = implode(' ', $values);
}
return $result;
}
Demo: http://codepad.viper-7.com/l8vmGr
Related
I am trying to implode the for each loop to get results like this
["86","87","88"]
Code I am using to achieve results as follows
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tag_data = $data->tag_id;
array_push($tags, $tag_data );
}
Use json_encode() to output that format:
echo json_encode($tags);
implode will change your data to a string.
$arr = ['1', '2', '3'];
$imp = implode(', ', $arr);
echo $imp; // output: 1, 2, 3
Probably, what you want is -
$tags = [];
$tagsData = $this->Constant_model->getDataOneColumn('snippets_tags', 'snippet_id', $id);
foreach ($tagsData as $data) {
$tags[] = $data->tag_id;
}
Hope it helps you. :)
I have a question here on how to parse a $POST_['value'] (e.g 3785,3789,3790,3787 ) from a form to an array($POST_['value']) and do foreach. Please see the sample code below:
function someFunction(){
$html = '';
$int = $_POST['Ids']; //POST the value as 3785,3789,3790,3787
$IDs = array($int);
foreach ($IDs as $ID) {
$intVal = '<int>' . $ID .'</int>';
$html .= $intVal;
}
return $html;
}
however the result displays it as the ****whole string** rather than array**.
And if I put the array(3785,3789,3790,3787) like this, it will parse as array in foreach. How to convert the $POST_['IDs'] to number or some sort in order to be recognised as array?
Thanks
Mike
This will work
function someFunction(){
$html = '';
$int = $_POST['Ids']; //POST the value as 3785,3789,3790,3787
$IDs = explode(',', $_POST['Ids']);
foreach ($IDs as $ID) {
$intVal = '<int>' . $ID .'</int>';
$html .= $intVal;
}
return $html;
}
You need to do a quick fix to the following line:
<?php
$IDs = explode(",", $int);
How can I rename an object property without changing the order?
Example object:
$obj = new stdClass();
$obj->k1 = 'k1';
$obj->k2 = 'k2';
$obj->k3 = 'k3';
$obj->k4 = 'k4';
Example rename by creating new property:
$obj->replace = $obj->k3;
unset($obj->k3);
Result:
( k1=>k1, k2=>k2, k4=>k4, replace=>k3 )
See the problem?
Simply recreating the object property causes the order to change.
I had a similar issue with arrays and came up with this solution:
Implemented solution for arrays
function replaceKey(&$array, $find, $replace)
{
if(array_key_exists($find, $array)){
$keys = array_keys($array);
$i = 0;
$index = false;
foreach($array as $k => $v){
if($find === $k){
$index = $i;
break;
}
$i++;
}
if ($index !== false) {
$keys[$i] = $replace;
$array = array_combine($keys, $array);
}
}
}
Looking for something similar to this but a function that will work on objects.
Can't seem to find any documentation on object property position indexes.
So, readd your properties
$obj = new YourClass();
$backup = [];
foreach ($obj as $key => $value)
{
$backup[$key] = $value;
unset($obj->$key);
}
replaceKey($backup, $find, $replace);
foreach ($backup as $key => $value)
{
$obj->$key = $value;
}
Since you have a function for your arrays, why dont you do something like :
$array = (array) $obj;
$replacedKeyArray = replaceKey($array);
$newObject = (object) $replacedKeyArray;
This is my $data variable:
cv = 1,2,3,4,5:::cpt = 4,5 ...
Now I need some function, where I can add the number as param (number will be $data number value).
for example.
function getPermission($id) {
... return $something;
}
Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.
So, to be clear:
if I call the function like this:
echo getPermission(4); output will be "cv" and "cpt".
but if I call it this way:
echo getPermission(1);
it'll only output "cv" because number (1) is located in the cv key.
Hope you guys understand, feel free to ask if something aren't clear enough.
$str = 'cv = 1,2,3,4,5:::cpt = 4,5';
$tmp = explode(':::', $str);
$data = array();
foreach ($tmp as $arr) {
$tokens = explode(' = ', $arr);
$data[$tokens[0]] = explode(',', $tokens[1]);
}
print_r(getPermission(4, $data));
print_r(getPermission(1, $data));
function getPermission($id, $data) {
$out = array();
foreach ($data as $key => $arr) {
if (in_array($id, $arr)) $out[] = $key;
}
return $out;
}
I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D