Display value of Array - php

I have this function :
$array = $um_followers->api->following( $currentid );
If I tried a var_dump :
var_dump($um_followers->api->following( $currentid ));
This is the result :
array(2) { [0]=> array(1) { ["user_id1"]=> string(1) "1" } [1]=> array(1) { ["user_id1"]=> string(2) "44" } }
1) I want to display the data 1 and 44 in the same line
2) I want to display the data 1 and 44 in the same line with a coma

you can do
echo implode(' ', array_column( $array,'user_id1'));
echo implode(', ', array_column( $array,'user_id1')); // with comma

well, something like this?
$array = array(
array("user_id1" => 1),
array("user_id1" => 44),
);
$line1 = "";
$line2 = "";
foreach($array as $smallArray){
$line1 .= $smallArray['user_id1'].' ';
$line2 .= $smallArray['user_id1'].', ';
}
$line1 = substr($line1, 0, -1); //delete last ' '
$line2 = substr($line2, 0, -2); //delete last ', '
echo $line1.'<br>';
echo $line2.'<br>';
it will echo this:
1 44
1, 44

Related

The string is converted to an array several times

I want to convert the string to an array.The following example.
1.Capitalize the first letter
2.The letter after ',' or '_' becomes capital
3.Strings are separated by ','
4.swap underline to ' '
$str_1 = "_ab,cb_ef,kk,uu";
$str_2 = ",cb_ef,kk,uu";
$str_3 = "cb_ef,kk,uu";
//convert to
$arr_1 = ('Ab','Cb Ef','Kk','Uu');
$arr_2 = ('Cb Ef','Kk','Uu');
$arr_3 = ('Cb Ef','Kk','Uu');
//There are my code and result .
$func = function( $str ){
$str_len = strlen( $str );
for ( $i = 0 ; $i < $str_len ; $i++ )
{
if ( $str[ $i ] == ',' && $str[ $i ] == '_' )
{
$str[ $i ] = $str[ $i ] == '_' ? ' ' : $str[ $i ] ;
if ( ord( $str[ $i +1 ] ) <= 122 && ord( $str[ $i +1 ] ) >= 97 )
{
$str[ $i ] = chr( ord( $str[ ++$i ] ) - 32 );
}
}
}
return $str;
};
var_dump(explode( ',' , $func( 'ss,adsa_sdfs' )));
//result is this
array(2) { [0]=> string(2) "ss" [1]=> string(9) "adsa_sdfs" }
Try this
function conv( $str ) {
$res = [];
$arr = explode( ',' , $str );
foreach ( $arr as $key => $value ) {
$res[] = ucwords( str_replace( '_' , ' ' , $value ) );
}
return $res;
}
var_dump( conv( 'ss,adsa_sdfs' ) );
Response:
array(2) { [0]=> string(2) "Ss" [1]=> string(9) "Adsa Sdfs" }
The demo code with your test cases:
<?php
function upper($s, $sep)
{
// upper the char separated by $sep
$a = explode($sep, $s);
$a = array_map('ucfirst', $a);
return join($sep, $a);
}
function test($s)
{
// upper the chars separated by '_'
$s = upper($s, '_');
// upper the chars separated by ','
$s = upper($s, ',');
// change all '_' to ' ' and upper the chars
$s = str_replace('_', ' ', $s);
$s = upper($s, ' ');
// trim unused chars
$s = trim($s, ' ,');
return explode( ',', $s);
}
$tests = [
"_ab,cb_ef,kk,uu" => ['Ab','Cb Ef','Kk','Uu'],
",cb_ef,kk,uu" => ['Cb Ef','Kk','Uu'],
"cb_ef,kk,uu" => ['Cb Ef','Kk','Uu'],
"ss,adsa_sdfs" => ['Ss', 'Adsa Sdfs'],
];
foreach ($tests as $s=>$a) {
$out = test($s);
if ($out === $a) {
echo "OK! $s = " . json_encode($a) . PHP_EOL;
} else {
echo "WRONG! $s is " . json_encode($out) . PHP_EOL;
}
}
Output:
OK! _ab,cb_ef,kk,uu = ["Ab","Cb Ef","Kk","Uu"]
OK! ,cb_ef,kk,uu = ["Cb Ef","Kk","Uu"]
OK! cb_ef,kk,uu = ["Cb Ef","Kk","Uu"]
OK! ss,adsa_sdfs = ["Ss","Adsa Sdfs"]
Write this
<?php
$str_1 = "_ab,cb_ef,kk,uu";
$str_2 = ",cb_ef,kk,uu";
$str_3 = "cb_ef,kk,uu";
function convert_to($arr){
$arr = str_replace('_', ' ', $arr);
$arr_1 = explode(",",$arr);
$new_array = array_map('trim', $arr_1);
$new_array = array_map('ucwords', $arr_1); // first letter after word capitalize
$new_array = array_filter($new_array, 'strlen'); // remove empty item
$new_array = array_values($new_array); // arrange and shift after removing empty item
return $new_array;
}
$arr_1 = convert_to($str_1);
$arr_2 = convert_to($str_2);
$arr_3 = convert_to($str_3);
var_dump($arr_1);
var_dump($arr_2);
var_dump($arr_3);
Output :
array(4) {
[0]=>
string(3) " Ab"
[1]=>
string(5) "Cb Ef"
[2]=>
string(2) "Kk"
[3]=>
string(2) "Uu"
}
array(3) {
[0]=>
string(5) "Cb Ef"
[1]=>
string(2) "Kk"
[2]=>
string(2) "Uu"
}
array(3) {
[0]=>
string(5) "Cb Ef"
[1]=>
string(2) "Kk"
[2]=>
string(2) "Uu"
}
You could use PHP's built-in functions for this kind of situation:
function processString($param){
$explode = explode(',', $param);
$replace = str_replace('_', ' ', $explode);
$replace = array_map('trim', $replace);
$ucfirst = array_map('ucwords', $replace);
return $ucfirst;
}
The explanation is:
First we convert the string to array based on comma separation using explode() method.
Next, we need to convert underscore into space using str_replace() method.
I noticed in your example that string with space (previously underscore) in it is stripped. This need to be implemented using trim(). Since the string already converted into array, we use array_map() method to process trim for all array values.
Finally, convert every word to uppercase. Fortunately, PHP already have the method: ucwords(). Just need to array_map() it.
This is how you test the code:
$str_1 = "_ab,cb_ef,kk,uu";
$str_2 = ",cb_ef,kk,uu";
$str_3 = "cb_ef,kk,uu";
print_r(processString($str_1));
print_r(processString($str_2));
print_r(processString($str_3));
Try the following code:
<?php
function ConvertToArr($str)
{
$result = array();
$temp_arr1 = explode(",", $str);
for ($count1 = 0; $count1 < count($temp_arr1); $count1++) {
$temp_results = array();
$temp_arr2 = explode("_", $temp_arr1[$count1]);
for ($count2 = 0; $count2 < count($temp_arr2); $count2++) {
$temp_str = ucfirst($temp_arr2[$count2]);
if ($temp_str != "")
$temp_results []= $temp_str;
}
$temp_results = implode(" ", $temp_results);
if (trim($temp_results) != "")
$result []= $temp_results;
}
return $result;
}
$str_1 = "_ab,cb_ef,kk,uu";
$str_2 = ",cb_ef,kk,uu";
$str_3 = "cb_ef,kk,uu";
print_r(ConvertToArr($str_1));
print_r(ConvertToArr($str_2));
print_r(ConvertToArr($str_3));
?>
It produces the following output:
Array
(
[0] => Ab
[1] => Cb Ef
[2] => Kk
[3] => Uu
)
Array
(
[0] => Cb Ef
[1] => Kk
[2] => Uu
)
Array
(
[0] => Cb Ef
[1] => Kk
[2] => Uu
)

foreach concatenate each element to next one

I would like to concatenate each element of array to next one. I want the output array to be:
Array
(
[0] => test
[1] => test/test2
[2] => test/test2/test3
[3] => test/test2/test3/test4
)
I tried the following way which concatenates each string to itself:
$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
foreach ($url as $dir) {
$dir .= $dir;
}
Any help appreciated.
Maybe another way
<?php
$data = array( 'test', 'test2', 'test3', 'test4' );
for( $i = 0; $i < count( $data ); $i++ )
{
if( $i != 0 )
{
$new[ $i ] = $new[ $i - 1 ] .'/'. $data[ $i ];
}
else
{
$new[ $i ] = $data[ $i ];
}
}
var_dump( $new );
Output
array(4) {
[0]=>
string(4) "test"
[1]=>
string(10) "test/test2"
[2]=>
string(16) "test/test2/test3"
[3]=>
string(22) "test/test2/test3/test4"
}
You should obtain the result you need in $my_array
$url = explode("/", "test/test2/test3/test4");
$str ='';
foreach($url as $key => $value){
if ( $str == '') {
$str .= $str;
} else {
$str .= '/'.$str;
}
$my_array[$key] = $str ;
echo $str . '<br />';
}
var_dump($my_array);
$url = preg_split("/[\s\/]+/", "test/test2/test3/test4");
$arr = array();
$str = '';
foreach ($url as $key => $dir) {
if ($key !== 0) {
$str .= '/' . $dir;
} else {
$str .= $dir;
}
$arr[] = $str;
}
On each iteration concate a string with new value and add it as a separate value for your output array.
Here's a quick way. For simple splitting just use explode():
$url = explode("/", "test/test2/test3/test4");
foreach($url as $value) {
$temp[] = $value;
$result[] = implode("/", $temp);
}
Each time through the loop, add the current value to a temporary array and implode it into the next element of the result.

Returning an INT value of data in an array

I have the result below of 2 arrays starting with [0] what I am wanting to do is return a result of "2" - As I have 2 "strings". How would I do this?
Result:
Array(1) {
[0]=> string(32) "b5cfec3e70d0d57ea848d5d8b9f14d61"
}
Array(1) {
[0]=> string(32) "eda80a3d5b344bc40f3bc04f65b7a357"
}
PHP:
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$cartDataArray = explode(" ", $cartData);
$result = $cartDataArray;
var_dump($result);
}
If I got this right, I think this is what you want:
$count = 0;
foreach($cart_contents as $key => $row) {
if(in_array($key, $skip))
continue;
$cartData = $row['rowid'];
$result = count(explode(" ", $cartData));
$count += $result;
}
var_dump($count);

How to loop over a string's characterss?

Basically, I have an array of strings, and I want to check if each character in each string is in a predefined $source string. Here is how I think it should be done:
$source = "abcdef";
foreach($array as $key => $value) {
foreach(char in $value) {
if(char is not in source)
unset($array[$key]); //remove the value from array
}
}
If this is a correct logic, how to implement the foreach and the if parts?
You could try this:
$array = array('1' => 'cab', '2' => 'bad', '3' => 'zoo');
$source = "abcdef";
foreach($array as $key => $value) {
$split = str_split($value);
foreach($split as $char){
$pos = strrpos($source, $char);
if ($pos === false) {
unset($array[$key]);
break;
}
}
}
Result:
array(2) {
[1]=>
string(3) "cab"
[2]=>
string(3) "bad"
}
DEMO: http://codepad.org/fU99Gdtd
Try this code:
$source = "abcdef";
foreach($array as $key => $value) {
$ichr = strlen($value) - 1;
// traverses each character in string
for($i=0; $i<$ichr; $i++) {
if(stristr($value{$i}) === false) {
unset($array[$key]);
break;
}
}
}
$array = array("abc","defg","asd","ade","de","fe");
$source = "abcde";
foreach ($array as $key => $string){
for($i=0;$i<strlen($string);$i++){
if(strpos($source, $string[$i])===false){
unset($array[$key]);
}
}
}
Now the array looks like
array(3) {
[0]=>
string(3) "abc"
[3]=>
string(3) "ade"
[4]=>
string(2) "de"
}
As I understand you want to filter ( remove ) the characters, that are not defined in the $source variable. By Mark Baker comments, this is what you need:
$source = str_split ( "abdef" ); //defined characters
$target = str_split ( "atyutyu" ); //string to be filtered
$result = array_intersect ( $target, $source );
echo implode( $result ); // output will be only "a"
And full example:
$source = str_split ( "abdef" );
$txts = array ( "alfa", "bravo", "charlie", "delta" );
function filter ( $toBeChecked, $against )
{
$target = str_split ( $toBeChecked );
return implode ( array_intersect ( $target, $against ) );
}
foreach ( $txts as &$value )
{
$value = filter ( $value, $source );
}
foreach ( $txts as $value )
{
echo $value . ", ";
}
//output afa, ba, ae, ae
$array = array(
'abacab',
'baccarat',
'bejazzle',
'barcode',
'zyx',
);
$source = "abcde";
$sourceArray = str_split($source);
foreach($array as $value) {
$matches = array_intersect($sourceArray, str_split($value));
echo $value;
if (count($matches) == 0) {
echo ' contains none of the characters ', $source, PHP_EOL;
} elseif (count($matches) == count($sourceArray)) {
echo ' contains all of the characters ', $source, PHP_EOL;
} else {
echo ' contains ', count($matches), ' of the characters ', $source, ' (', implode($matches), ')', PHP_EOL;
}
}
gives
abacab contains 3 of the characters abcde (abc)
baccarat contains 3 of the characters abcde (abc)
bejazzle contains 3 of the characters abcde (abe)
barcode contains all of the characters abcde
zyx contains none of the characters abcde

Suggestions for parsing this data

So I have a huge file of names that has to be split into more columns for excel.
So I am using PHP to parse this, so here is part of the example:
Dr. Johnny Apple Seed
Ms. A. P. Oranges
Mrs. Purple Cup
Essentially, I want to put this into an array. I was using fopen, fget, and explode. The problem is, if I use explode, some of the arrays would not have consistent elements. For example, the first one would have a total of 4 (Dr, Johnny, Apple, Seed), the third would have only three. How would I add a fourth empty element between purple and cup? or is there a better way?
This is my code:
$fp = fopen($filename,"r");
if ($fp) {
while (!feof($fp)) {
$data = fgets($fp, filesize($filename));
$contents[] = explode(" ", $data) .
}
}
fclose($fp);
echo "<pre>";
var_dump($contents);
echo "</pre>";
Desired Output:
array(4) {
[0]=>
string(4) "Mrs."
[1]=>
string(4) "Purple"
[2]=>
string(1) " "
[3]=>
string(8) "Cup"
array(4) {
[0]=>
string(3) "Dr."
[1]=>
string(6) "Johnny"
[2]=>
string(5) "Apple"
[3]=>
string(4) "Seed"
Try this (haven't tested but should work):
// Define the clean array
$clean_array = array();
$fp = fopen($filename,"r");
if ($fp) {
while (!feof($fp)) {
$data = fgets($fp, filesize($filename));
// use trim() on $data to avoid empty elements
$contents = explode(" ", trim($data));
if (count($contents) == '3') {
// Copy last element to new last element
$contents[] = $contents[2];
// Clear the old last element
$contents[2] = ' ';
}
$clean_array[] = $contents;
}
}
fclose($fp);
echo '<pre>';
print_r($clean_array);
echo '</pre>';
Hope this helps.
This should work:
<?php
$new_array = array();
$fp = fopen($filename, "r");
if ($fp) {
while (!feof($fp)) {
$data = fgets($fp, filesize($filename));
$contents[] = explode(" ", $data);
}
}
foreach ($contents as $content) {
if (count($content) != 4) {
$content[3] = $content[2];
$content[2] = " ";
$new_array[] = $content;
}
else {
$new_array[] = $content;
}
}
fclose($fp);
echo "<pre>";
var_dump($new_array);
echo "</pre>";
?>
If they are newlines, you can just use "\n" as the $needle
I used array_splice, here is my solution:
<?php
$filename = "excel-names.txt";
$fp = fopen($filename,"r");
if ($fp) {
while (!feof($fp)) {
$data = fgets($fp, filesize($filename));
$contents[] = explode(" ", $data, 4);
}
}
fclose($fp);
foreach( $contents as $a) {
$arrayCount = count($a);
if( $arrayCount == 3 ) {
array_splice($a, 2, 0, " ");
}
if( $arrayCount == 2 ) {
array_splice($a, 0, 0, " ");
array_splice($a, 2, 0, " ");
}
}
?>

Categories