return array from function php - php

I need this function to return an array. When I call the function it is printing the array, but when I use return $finalResult in the function, it is only printing the first array.
function readData($file)
{
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach ($textLines as $line)
{
$expLine = explode("\t", $line);
if (count($expLine) < 8)
{
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" => $expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr = $finalResult;
print_r($arr);
}
}

Hi You mush merge or push array to $finalResult see sammple
function readData($file){
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
//Here []
$finalResult[] = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
//$arr=$finalResult;
//print_r($arr);
}
return $finalResult;
}

As described in my comment above
function readData($file){
$arr = array();
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr=array_merge($arr, $finalResult);
}
return $arr;
}

Related

How to echo all values from a specific array?

This is what I'm doing:
for($i = 0; $i <= $max; $i++) {
if(isset($media[$i])) {
$combined[] = ["type" => "media", "value" => $media[$i]];
}
if(isset($content[$i])) {
$combined[] = ["type" => "content", "value" => $content[$i]];
}
if(isset($yt[$i])) {
$combined[] = ["type" => "youtube", "value" => $yt[$i]];
}
}
echo implode(', ', array_column($combined, 'media'));
Basically I need to echo all values of "media" as a single string with value separated commas.
Tried this too:
echo implode(', ', array_map(function ($entry) {
return $entry['media'];
}, $combined));
$string = '';
foreach ( $combined as $com ) {
if ( $com['type'] === 'media' ) {
$string .= $com['value'] . ',';
}
}
$string = rtrim( $string, ','); // remove trailing comma
echo $string;

Convert array index in a custom string layout?

I have an array called $context with this structure:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Foo"
["username"]=>
string(6) "Test"
}
[1]=>
array(2) {
["name"]=>
string(4) "John"
["username"]=>
string(3) "Doe"
}
}
I want convert it into this string:
string 1:
0: array(
'name' => 'Foo',
'username' => 'Test',
)
string 2:
1: array(
'name' => 'John',
'username' => 'Doe',
)
How you can see I want save the current index in the iteration and display the array content formatted as 'name' and 'username' in a single line. I already tried with this code:
$export = '';
foreach($context as $key => $value)
{
$export .= "{$key}: ";
print_r($value);
$export .= preg_replace(array(
'/=>\s+([a-zA-Z])/im',
'/array\(\s+\)/im',
'/^ |\G /m'
), array(
'=> $1',
'array()',
' '
), str_replace('array (', 'array(', var_export($value, true)));
print_r($export);
$export .= PHP_EOL;
}
return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
but I'm looking for a more optimized solution, any suggest?
This is my code:
$context = [['name'=>'Foo','username'=>'Test'],['name'=>'John','username'=>'Doe']];
$schema = " '%s' => '%s'";
$lineBreak = PHP_EOL;
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
echo $output.$lineBreak;
}
3v4l.org demo
It will works independently from the number of elements in sub-arrays
I have used classic built-in function sprintf to format each array row: see more.
You can change $lineBreak with you preferred endLine character;
In the above example, each string is printed, but (you have a return in your function, so i think inside a function), you can modify in this way:
$output = array();
foreach( $context as $idx => $array )
{
(...)
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
to have an array filled with formatted string.
You can easly transform it in a function:
function contextToString( $context, $schema=Null, $lineBreak=PHP_EOL )
{
if( !$schema ) $schema = " '%s' => '%s'";
$output = array();
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
return implode( $lineBreak, $output );
}
to change each time the schema and the line break.
PS: I see that in you code there is a comma also at the end of the last element of eache array; thinking it was a typo, I have omitted it
Edit: I have forgot the comma, added-it.
Edit 2: Added complete function example.
Edit 3: Added link to sprintf PHP page
Try this with personnal toString
$a = array(array("name"=>"Foo", "username"=>"Test"), array("name"=>"John", "username"=>"Doe"));
function toString($array){
$s = ""; $i=0;
foreach ($array as $key => $value) {
$s.= $key."=>".$value;
if($i < count($array)-1)
$s.=",";
$i++;
}
return $s;
}
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . toString($value).")");
$index ++;
}
var_dump($result);
And the result :
array (size=2)
0 => string '0 : array(name=>Foo,username=>Test)' (length=35)
1 => string '1 : array(name=>John,username=>Doe)' (length=35)
The result is in an array but you can change and make what you want
But you can also use json_encode :
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . json_encode($value).")");
$index ++;
}
var_dump($result);
With this result :
array (size=2)
0 => string '0 : array({"name":"Foo","username":"Test"})' (length=43)
1 => string '1 : array({"name":"John","username":"Doe"})' (length=43)
Simplified solution with strrpos,substr_replace and var_export:
$arr = [
array(
'name' => 'John',
'username' => 'Doe'
),
array(
'name' => 'Mike',
'username' => 'Tyson'
)
];
/*****************/
$strings = [];
foreach($arr as $k => $v){
$dump = var_export($v, true);
$last_comma_pos = strrpos($dump,",");
$cleared_value = substr_replace($dump, "", $last_comma_pos, 1);
$strings[] = $k.": ".$cleared_value;
}
/*****************/
// Now $strings variable contains all the needed strings
echo "<pre>";
foreach($strings as $str){
echo $str . "\n";
}
// the output:
0: array (
'name' => 'John',
'username' => 'Doe'
)
1: array (
'name' => 'Mike',
'username' => 'Tyson'
)

PHP Using an If-else inside multidimensional associative array

My multidimensional associative array :
$search_cookies = array(
"type_catalog" => $type_array,
"size_catalog" => $size_array,
"color_catalog" => $color_array,
);
I need to do that :
$search_cookies = array(
if(isset($type_array){
"type_catalog" => $type_array,
}
elseif(isset($size_array)){
"size_catalog" => $size_array,
}
elseif(isset($color_array)){
"color_catalog" => $color_array,
}
);
Here is the entire code if you think it must be some other way :
$first_array = array('t-1', 's-32', 't-2', 's-36');
function removeLetters($row){
return preg_replace("/[^0-9,.]/", "", $row);
}
foreach($first_array as $row){
$exp_key = explode('-', $row);
if($exp_key[0] == 't'){
$type_array[] = removeLetters($row);
}
if($exp_key[0] == 's'){
$size_array[] = removeLetters($row);
}
if($exp_key[0] == 'c'){
$color_array[] = removeLetters($row);
}
}
$search_cookies = array(
"type_catalog" => $type_array,
"size_catalog" => $size_array,
"color_catalog" => $color_array,
);
you can try this:
$search_cookies = array();
if(isset($type_array)){
$search_cookies["type_catalog"] = $type_array;
}
if(isset($size_array)){
$search_cookies["size_catalog"] = $size_array;
}
if(isset($color_array)){
$search_cookies["color_catalog"] = $color_array;
}

Imploding with "and" in the end?

I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>

How Can I Convert a Multidimensional Array in Php to XML

I have an array like
$a = array(
'aaa' => "sample",
'bbb' => "sample2",
'ccc' => "adas",
'ddd' => "2",
'eee' => '2013-09-05',
'fff' => "false",
'ggg' => "893",
'qqq' => '2013-09-05',
'sss' => array(
"iii" => array(
'vvv' => "sample3",
'xxx' => 500,
)
),
'nnn' => '2013-09-05',
'mmm' => "Normal",
);
and I want to convert it to xml but witout using SimpleXMLElement or another function. That's why I have tried to do it with foreach. Here is my code ;
$data = '';
foreach ($a as $k => $v) {
if (is_array($k)) {
$data .= "<a:$k>" . $v . "</a:$k>";
foreach ($k as $j => $m) {
if (is_array($j)) {
foreach ($j as $s => $p) {
$data .= "<a:$s>" . $p . "</a:$s>";
}
} else {
$data .= "<a:$j>" . $m . "</a:$j>";
}
}
} else {
$data .= "<a:$k>" . $v . "</a:$k>";
}
}
but it's not working. I can make it work with hashmaps in another language but it must be in php. How can I do this.
Thanks.
You could try this:
function createXml($array, $level = 0)
{
$xml = ($level == 0) ? '<?xml version="1.0" encoding="ISO-8859-1"?>'.PHP_EOL : '';
$tab = str_pad('', $level, ' ', STR_PAD_LEFT);
foreach($array as $node => $value)
{
$xml .= "{$tab}<{$node}>";
if(!is_array($value))
{
$xml .= $value;
}
else
{
$level++;
$xml .= PHP_EOL.createXml($value, $level).$tab;
}
$xml .= "</{$node}>".PHP_EOL;
}
return $xml;
}
$xml = createXml($a);
echo $xml;

Categories