I have an array that looks like this:
Array
(
[0] => stdClass Object
(
[user_id] => 10
[date_modified] => 2010-07-25 01:51:48
)
[1] => stdClass Object
(
[user_id] => 16
[date_modified] => 2010-07-26 14:37:24
)
[2] => stdClass Object
(
[user_id] => 27
[date_modified] => 2010-07-26 16:49:17
)
[3] => stdClass Object
(
[user_id] => 79
[date_modified] => 2010-08-08 18:53:20
)
)
and what I need to do is print out the user id's comma seperated so:
10, 16, 27, 79
I'm guessing it'd be in a for loop but i'm looking for the most efficient way to do it in PHP
Oh and the Array name is: $mArray
I'm trying the methods below but I keep getting this error: Fatal error: Cannot use object of type stdClass as array in
$length = sizeof($mArray);
sort($mArray);
foreach($mArray as $item)
{
echo $item['user_id'] . ($item !== $mArray[$length]) ? ', ' : '';
}
Remove the sort if you don't need it in order.
Whenever I need to make a delimited list (in this case by a comma), I start with an array and implode() it with the delimiter. In this case the delimiter would be the comma + the space:
$user_ids = array();
foreach($mArray as $item) {
$user_ids[] = $item['user_id'];
}
$comma_delimited_list = implode(', ', $user_ids);//magic
$firstTime = true;
foreach($mArray as $k => $cur)
{
//echo $firstTime ? $firstTime = false : ', '; //this one-liner cna replace the following two, kind of unclear but i like it
if (!$firstTime) echo ', ';
else $firstTime = false;
echo $cur->user_id;
}
This is more fun:
$f = function($a,$b) {$c = $a ? ', ' : ''; return $a . $c . $b->user_id;};
echo array_reduce($f, $mArray, '');
James alludes to using join, which is a good idea and avoids the trailing comma issue
$newArr = array_map(function($x) {return $x->user_id;}, $mArray); //make array of just user-ids
echo join(', ',$newArr); // implode === join, join is an alias of implode
I'd do it like this:
$output = "";
foreach($mArray as $i => $val) {
$output .= $val->user_id . ", " ;
}
$output = trim($output, ", ");
Heck, you could probably use join and remove the foreach loop altogether!
Related
I have a Laravel installed with Moloquent (Mongo). Mongo ins't necessarily the problem, when the model loads the "JSON" record, it becomes a PHP associative array.
I need to be able to create a function in a model that returns an array element by a string.
for example:
$search1 = 'folder1/folder2/folder3/item';
//would look like: $array['folder1'][folder2'][folder3']['item']
$search2 = 'folder1/picture1/picture';
//would look like: $array['folder1'][picture1']['picture']
echo getRecord($search1);
echo getRecord($search2);
function getRecord($str='') {
//this function take path as string and return array
return $result;
}
I guess I could use the ?? operator, but I have to form an array "check" meaning:
How would I form the $array['1']['2']['3'] if I have 3 elements deep or 1 ($array['1']), or 5 ($array['1']['2']['3']['4']['5']).
I am making an api to add an item or folder to Mongo.
Input : "f1/f2/item"
This function I have:
echo print_r($j->_arrayBuilder('f1/f2/item'), true);
public function _arrayBuilder($folderPath)
{
$ret = array();
$arr = explode('/', $folderPath);
Log::info("Path Array:\n" . print_r($arr, true));
$x = count($arr) - 1;
Log::info("Count: " . $x);
for ($i = 0; $i <= $x; $i++) {
Log::info("Element of arr: " . $arr[$i]);
$ret = array($arr[$i] => $ret);
}
return $ret;
}
Current output:
Array
(
[item] => Array
(
[f2] => Array
(
[f1] => Array
(
)
)
)
)
Desire output:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Note: I have tried PHP's array_reverse and it does not work on this.. Multidimensional and non-numeric..
Thank you.
If I understand correctly, You want to take input string f1/f2/f3/f4/f5/item and create array("f1" => array("f2" => array("f3" => array("f4" => array("f5" => array("item" => array()))))))
In order to do that you can use function close to what you tried as:
function buildArr($path) {
$path = array_reverse(explode("/", $path)); // getting the path and reverse it
$ret = array();
foreach($path as $key)
$ret = array($key => $ret);
return $ret;
}
For input of print_r(buildArr("f1/f2/item")); it prints:
Array
(
[f1] => Array
(
[f2] => Array
(
[item] => Array
(
)
)
)
)
Hope that what you meant. If not feel free to comment
I want to remove the last few letters from an array in a for-each loop. I am trying to show bl_date without /2018. Now its showing 07/10/2018 & 06/30/2018. How can echo like this 07/10 & 06/30?
Array
Array
(
[0] => stdClass Object
(
[id] => 18
[bl_user] => 61
[bl_date] => 07/10/2018
)
[1] => stdClass Object
(
[id] => 17
[bl_user] => 61
[bl_date] => 06/30/2018
)
)
PHP
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = $billing->bl_date;
}
echo implode(" & ",$resultstr);
One option is to use substr() to remove the last 5 characters of the string
Like:
$resultstr = array();
foreach ($billings as $billing) {
$resultstr[] = substr( $billing->bl_date, 0, -5 );
}
echo implode(" & ",$resultstr);
This will result to:
07/10 & 06/30
Doc: substr()
You need to use substr function:
foreach ($billings as $billing) {
$resultstr[] = substr($billing->bl_date, 0, 5);
}
I've got a multidimensional array.
I need a way to tally up the total value when both the 1st and second strings in the array occur multiple times.
So for instance :
Gold Metallic = 22
Black Toscano = 26
etc...
Any ideas?
[0] => Array
(
[0] => Array
(
[0] => Black
[1] => Toscano
[2] => 14
)
[1] => Array
(
[0] => Gold
[1] => Metallic
[2] => 10
)
)
[1] => Array
(
[0] => Array
(
[0] => Gold
[1] => Metallic
[2] => 12
)
[1] => Array
(
[0] => Black
[1] => Toscano
[2] => 12
)
)
This just solves the problem for your data structure so you have to make sure that, in practice, every two items you will get a number. Hope you can learn something from this :)
$products = array(
array(
array("Black", "Toscano", 14),
array("Gold", "Metallic", 10)
),
array(
array("Black", "Toscano", 12),
array("Gold", "Metallic", 12)
),
);
$accumulated = array();
$key = "";
$callback = function($item, $index) use(&$key, &$accumulated) {
if($index != 2) {
$key .= $item;
} else {
if(!array_key_exists($key, $accumulated)) {
$accumulated[$key] = 0;
}
$accumulated[$key] += $item;
$key = "";
}
};
array_walk_recursive($products, $callback);
var_dump($accumulated);
Should be a simple case of looping over the data and storing an array of sums. This is one possibility using a hash with keys as the pairs concatenated with a separator sentinel value.
$separator = "||"; //take care to choose something that doesn't pop up in your data here
//$data = example data;
$pairs = array();
foreach ($data as $val) {
foreach ($val as $pair) {
$str = $pair[0] . $separator . $pair[1];
if (array_key_exists($str, $pairs))
$pairs[$str] += $pair[2];
else
$pairs[$str] = $pair[2];
}
}
print_r($pairs);
output:
["Black||Toscano"] => 26,
["Gold||Metallic"] => 22
The data can be easily retrieved at this point
foreach ($pairs as $str => $sum) {
$str = explode($separator, $str);
echo $str[0] . ", " . $str[1] . ": " . $sum;
}
I have a PHP array with multiple objects. I'm trying to join values from a certain key into one string separated by commas. Output from var_dump:
Array
(
[0] => stdClass Object
(
[tag_id] => 111
[tag_name] => thing 1
[tag_link] => url_1
)
[1] => stdClass Object
(
[tag_id] => 663
[tag_name] => thing 2
[tag_link] => url_2
)
)
The string needs to be $string = 'thing 1,thing 2'. I tried using a foreach loop, but I'm completely stuck. Could anyone help out?
The above answer is a little light, maybe run it as a foreach loop instead.
$names = array();
foreach ($array as $k => $v) {
$names[] = $v->tag_name;
}
$string = implode(',', $names);
$output = '';
foreach($test as $t){
$output .= $t->tag_name . ',';
}
$output = substr($output, 0, -1);
echo $output;
Try as this
$string = $array[0]->tag_name.','.$array[1]->tag_name;
For other elements
$string = '';
foreach($array as $object) $string.=$object->tag_name.',';
$string = substr($string,0,-1);
Use something like this:
implode(',', array_map(function ($el) {
return $el->tag_name;
}, $array));
my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.