print array with explode function..? - php

Hi guys i have a problem when i want to "print_r" my variable string that i've "explode". the detail is below..
$var = "1,2,3,4,5";
$sat = explode(',',$var);
echo"`<pre>`";
print_r($sat);
i want to have result like this...
Array
(
[0] => Array
(
[new] => 1
)
[1] => Array
(
[new] => 2
)
[2] => Array
(
[new] => 3
)
[4] => Array
(
[new] => 4
)
...
)
but when i'm tried my script, it was not same like above. what is wrong with my script and what should i do guys so the result of the array can be the same like above. Please help me guys!

Use array_map to bulid the child arrays. see array_map
Try closing pre tag. When you are dumping the array in your browser, you are relying on the browser to format your array. But you are not closing the pre tag , and this doesn't help html to format the array!
$var = "1,2,3,4,5";
$sat = explode(',', $var);
$sat = array_map("buildArray", $sat);
dump($sat);
function buildArray($value)
{
return array(
'new' => $value
);
}
function dump($res)
{
echo '<pre>';
print_r($res);
echo '</pre>';
}

$var = "1,2,3,4,5";
$sat = explode(',',$var);
$sat = array_map(function($value) { return array('new' => $value); }, $sat );
var_dump($sat);

$var = "1,2,3,4,5";
$sat = explode(',',$var);
function p($value) { return array('new' => $value); }
$sat = #array_map(p, $sat );
echo("<pre>");
print_r($sat);
echo("</pre>");

Related

Create PHP array from string for Mongo

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

parse_str array return only last value

I am using ajax to submit the form and ajax value post as:
newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14
In PHP I am using parse_str to convert string to array,but it return only last value:
$newcoach = "newcoach=6&newcoach=11&newcoach=12&newcoach=13&newcoach=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
Result array having only last value:
Array
(
[newcoach] => 14
)
Any help will be appreciated...
Since you set your argument newcoach multiple times, parse_str will only return the last one. If you want parse_str to parse your variable as an array you need to supply it in this format with a '[ ]' suffix:
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
Example:
<?php
$newcoach = "newcoach[]=6&newcoach[]=11&newcoach[]h=12&newcoach[]=13&newcoach[]=14";
$searcharray = array();
parse_str($newcoach, $searcharray);
print_r($searcharray);
?>
Outputs:
Array ( [newcoach] => Array ( [0] => 6 [1] => 11 [2] => 12 [3] => 13 [4] => 14 ) )
Currently it is assigning the last value as all parameter have same name.
You can use [] after variable name , it will create newcoach array with all values within it.
$test = "newcoach[]=6&newcoach[]=11&newcoach[]=12&newcoach[]=13&newcoach[]=14";
echo '<pre>';
parse_str($test,$result);
print_r($result);
O/p:
Array
(
[newcoach] => Array
(
[0] => 6
[1] => 11
[2] => 12
[3] => 13
[4] => 14
)
)
Use this function
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$parsed_array = proper_parse_str($newcoach);

Can't remove empty elements from array

I want to remove empty elements from an array. I have a $_POST-String which is set to an array by explode(). Then I'am using a loop to remove the empty elements. But that does not work. I also tried array_filter(), but with no succes. Can you help me? See Code below:
$cluster = explode("\n", $_POST[$nr]);
print_r ($cluster);
echo "<br>";
for ($i=0 ; $i<=count($cluster);$i++)
{
if ($cluster[$i] == '')
{
unset ( $cluster[$i] );
}
}
print_r ($cluster);
echo "<br>";
Result:
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => [5] => )
Array ( [0] => Titel1 [1] => Titel2 [2] => Titel3 [3] => [4] => )
Empty elements can easily be removed with array_filter:
$array = array_filter($array);
Example:
$array = array('item_1' => 'hello', 'item_2' => '', 'item_3' => 'world', 'item_4' => '');
$array = array_filter($array);
/*
Array
(
[item_1] => hello
[item_3] => world
)
*/
The problem ist that the for loop condition gets evaluated on every run.
That means count(...) will be called multiple times and every time the array shrinks.
The correct way to do this is:
$test = explode("/","this/is/example///");
print_r($test);
$arrayElements = count($test);
for($i=0;$i<$arrayElements;$i++)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
An alternative way without an extra variable would be counting backwards:
$test = explode("/","this/is/example///");
print_r($test);
for($i=count($test)-1;$i>=0;$i--)
if(empty($test[$i])
unset($test[$i]);
print_r($test);
What if you change:
for ($i=0 ; $i<=count($cluster);$i++) { if ($cluster[$i] == '') { unset ( $cluster[$i] ); } }
to
for ($i=0 ; $i<=count($cluster);$i++) { if (trim($cluster[$i]) == '') { unset ( $cluster[$i] ); } }

Reproducing the new array from existing array(multi array)

Reproducing the new array from existing array(multi array)
If I have an array called as parameter:
$arr = Array
(
[0] => Array(0,Array(0=>'abc'))
[1] => Array(0,Array(1=>'def'))
[2] => Array(1,Array(0=>'ghi'))
)
Want to to a function that pass $arr some thing like this
function TODO($arr){
//
return $new_array;
}
And the function will return
RESULT WILL BE Reproduce elements from previous array ,And it will be got the result(returned):
Array
(
[0] => Array
(
[0] => 'abc'
[1] => 'def'
)
[1] => Array
(
[0] => 'ghi'
)
)
Anybody know how to do this?Please
thanks
I'm not 100% sure I've understood what you want, but if I have, this should work:
<?php
$arr = Array(
0 => Array(0, Array(0=>'abc')),
1 => Array(0, Array(1=>'def')),
2 => Array(1, Array(0=>'ghi'))
);
function transformArray($array) {
$newArray = array();
foreach ($array as $value) {
if (!isset($newArray[$value[0]])) {
$newArray[$value[0]] = array();
}
$newArray[$value[0]][] = array_pop($value[1]);
}
return $newArray;
}
$outputArray = transformArray($arr);
echo '<pre>' . print_r($outputArray, true) . '</pre>';
?>
I don't think so. If you have controll over how these text arrays are turned into text, you should use serialize() and unserialize(). The fastest and easiest way.
If you still need to create arrays from the strings you have provided, you will probably have to construct quite a complex function to do that.

create new array from a multidimensional array

I have this multidimensional array:
Array (
[0] => Array (
[id] => 1
[list_name] => List_Red
)
[1] => Array (
[id] => 2
[list_name] => List_Blue
)
)
...and i would like to create a new array containing only the [id]'s from it.
I would appreciate it alot if you guys could help me with that ^^
Thanks in advance.
#fabrik Your solution indeed does work but it is also incorrect as PHP will throw a E_WARNING telling you that you're appending to an array that did not yet exist. Always initialise your variables before you use them.
$newList = array();
foreach($myList as $listItem) {
$newList[$listItem['id']] = $listItem['list_name'];
}
This is now a list of all your list_names in the following format.
Array (
1 => List_Red
2 => List_Blue
)
Much easier for you to work with and you can now iterate over it like so..
foreach($newList as $itemID => $itemName) {
echo "Item ID: $itemID - Item Name: $itemName<br>";
}
You could use array_map like this:
$new_array = array_map( function( $a ) { return $a['id']; }, $orig_array );
That's assuming PHP 5.3, for PHP < 5.3 you have to use create_function:
$new_array = array_map( create_function( '$a', 'return $a["id"];' ), $orig_array );
foreach($array as $label => $data)
{
$final[] = $data['id'];
}

Categories