Joining array values into string - php

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));

Related

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

explode associative array in php and adding two fields in the array

output of form:
Array (
[0] => (19.979802102871425,73.78671169281006)
[1] => (19.97978382724978,73.78682289971039)
[2] => (19.979765551626006,73.78697712672874)
)
expect output:
Array (
[0] =>
[lag]=>19.979802102871425,
[long]=>73.78671169281006,
[1] => [lag]=>19.97978382724978,
[long]=>73.78682289971039
[2] => [lag]=>19.979765551626006,
[long]=>73.78697712672874
)
following code working is not given me desired output as i am unaware of adding two associate element in array
foreach($_POST['textbox'] as $value):
$value = str_replace(array('(',')'), '',$value);
foreach (explode(',', $value) as $topic) :
list($name, $items) =$topic;
///stuck up here
}
$test[] = explode(',', $value);
endforeach;
endforeach;
could please suggest the changes in the code as i reffered following links but the expected out is different from mine.thanks in advance
php-explode-and-put-into-array
explode-function
You can try this -
foreach($your_array As &$array) {
$temp = explode(',', str_replace(array('(', ')'), '', $array)); // replace the ()s & explode the value
$array = array('lat' => $temp[0], 'long' => $temp[1]); // store with keys
}
Try this :
foreach($array as $value){
list($lat,$lng) = explode(',',trim(trim($value,')'),'('));
$out[] = array( 'lat' => $lat , 'lng' => $lng);
}
var_dump($out);

Big string to nice array

I need to make big string into a nice array. String itself is list of tags and tag ids. There can be any amount of them. Here is example of the string: 29:funny,30:humor,2:lol - id:tag_name. Now, I have problem converting it to array - Array ( [29] => funny [30] => humor ). I can get to the part where tags are as so
Array (
[0] = Array (
[0] = 29
[1] = funny
)
[1] = Array (
[0] = 30
[1] = humor
)
)
I've look at array functions too but seems none of them could help me.
Can anyone help me out?
Here's some code to get you going:
$str = "29:funny,30:humor,2:lol";
$arr = array();
foreach (explode(',', $str) as $v) {
list($key, $val) = explode(':', $v);
$arr[$key] = $val;
}
print_r($arr);
/* will output:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
*/
You could replace the foreach with an array_map for example, but I think it's simpler for you this way.
Here's an example of it working: http://codepad.org/4BpnCiEJ
You could use explode() to do this, though it would take two passes. The first to split the string into pairings (explode (',', $string)) and the second to split each paring
$arr = explode (',', $string);
foreach ($arr as &$pairing)
{
$pairing = explode (':', $pairing);
}
$string = '29:funny,30:humor,2:lol';
$arr1 = explode(',', $string);
$result = array();
foreach ($arr1 as $element1) {
$result[] = explode(':', $element1);
}
print_r($result);
You can use preg_match_all
preg_match_all('#([\d]+):([a-zA-Z0-9]+)#', $sString, $aMatches);
// Combine the keys with the values.
$aArray = array_combine($aMatches[1], $aMatches[2]);
echo "<pre>";
print_r($aArray);
echo "</pre>";
Outputs:
Array
(
[29] => funny
[30] => humor
[2] => lol
)
<?php
$test = '29:funny,30:humor,2:lol';
$tmp_array = explode(',', $test);
$tag_array = ARRAY();
foreach ($tmp_array AS $value) {
$pair = explode(':', $value);
$tag_array[$pair[0]] = $pair[1];
}
var_dump($tag_array);
?>

PHP Array Looping

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!

weird php 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.

Categories