PHP explode array - php

I'm trying to get random values out of an array and then break them down further, here's the initial code:
$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );
$rand = array_rand($in, 3);
$in[$rand[0]]; //foo_1|bar_1
$in[$rand[1]]; //foo_3|bar_3
$in[$rand[2]]; //foo_5|bar_5
What I want is same as above but with each 'foo' and 'bar' individually accessible via their own key, something like this:
$in[$rand[0]][0] //foo_1
$in[$rand[0]][1] //bar_1
$in[$rand[1]][0] //foo_3
$in[$rand[1]][1] //bar_3
$in[$rand[2]][0] //foo_5
$in[$rand[2]][1] //bar_5
I've tried exploding $rand via a foreach loop but I'm obviously making some n00b error:
foreach($rand as $r){
$result = explode("|", $r);
$array = $result;
}

You were close:
$array = array();
foreach ($in as $r)
$array[] = explode("|", $r);

Try this...
$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );
foreach($in as &$r){
$r = explode("|", $r);
}
$rand = array_rand($in, 3);
That modifies $in "on the fly", so it contains the nested array structure you're looking for.
Now...
$in[$rand[0]][0] //foo_1
$in[$rand[0]][1] //bar_1
$in[$rand[1]][0] //foo_3
$in[$rand[1]][1] //bar_3
$in[$rand[2]][0] //foo_5
$in[$rand[2]][1] //bar_5
I think that's what you're looking for.

foreach($rand as $r){
$result = explode("|", $r);
array_push($array, $result);
}

Related

how to get value of key in php associative array by comparing key with a string to get value?

I have below small PHP script, I just need the value from the array if I provide key in $str.
$empid_array = array('CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal');
$key = array();
$value = array();
$str = "CIP004";
foreach($empid_array as $code){
$str = preg_split("/\-/", $code);
array_push($key, $str[0]);
array_push($value, $str[1]);
}
$combined = array_combine($key, $value);
echo count($combined);
foreach($combined as $k => $v){
if($str == $k){
echo $v;
}
}
You could simplify your code considerably here. Step one, use array_walk to walk through the array and build the $combined array. Step two, there's no point in looping through the array, just access the value by the index:
$empid_array = ['CIP004 - Rinku Yadav', 'CIP005 - Shubham Sehgal'];
$str = "CIP004";
$combined = [];
// passing $combined by reference so we can modify it
array_walk($empid_array, function ($e) use (&$combined) {
list($id, $name) = explode(" - ", $e);
$combined[$id] = $name;
});
echo $combined[$str] ?? "Not found";

Dynamically generating foreach

I'm trying to write a function that do the following :
Let's say i have an array :
$data = array(
array('10','15','20','25'),
array('Blue','Red','Green'),
array('XL','XS')
)
and my result array should be like :
$result = array(
array('10','15','20','25'),
array('Blue','Red','Green','Blue','Red','Green','Blue','Red','Green','Blue','Red','Green')
array('XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS')
)
Im stuck with this because i want a function that is able to do this no matter how much array there is in the first array $data
I have only been able to write this, which is what give the $result array :
foreach($data[2] as $value2){
$result[2][] = $value2;
foreach($data[1] as $value1){
$result[1][] = $value1;
foreach($data[0] as $value0){
$result[0][] = $value0;
}
}
}
After a few research, it seems that a recursive function is the way to go in order to dynamically generate those foreach but i can't get it to work.
Thanks for your help.
This is dynamic:
$result[] = array_shift($data);
foreach($data as $value) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
Get and remove the first element from original
Loop remaining elements and fill result with values X number of values in first element
Since the elements were arrays merge them all into result
If modifying the original is unwanted, then use this method:
$result[] = reset($data);
while($value = next($data)) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
just use array_fill and array_merge functions
$result = array(
$data[0],
array_merge(...array_fill(0,count($data[0]), $data[1])),
array_merge(...array_fill(0,count($data[0])*count($data[0]), $data[2]))
);
print_r($result);
demo on eval.in

PHP: Sort array by exploded value

How can I sort an array by a value from an exploded string?
To make it a bit more clear, I have data stored in a textfile in the following format:
Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
Value_1|Value_2|Value_3|Value_4|Value_5
...
I read the data using
$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);
then explode each line and output the content (HTML stripped to keep it clean)
foreach ($lines as $line_num => $dataset) {
$dataset = explode('|', $dataset);
//echo exploded values + some HTML
}
However, before I output the data, I want to sort the array by Value_2 (which is always a number) from e.g. high to low. Do I have to set the keys of the array to Value_2 and then sort it? How can I do that? What would be the best solution here?
Thanks for your help!
This is the final, slightly modified snippet for everyone who's interested:
$data_file = 'foo.txt';
$lines = file($data_file, FILE_IGNORE_NEW_LINES);
function sort_data_array($a, $b){
$ex_a = explode('|', $a);
$ex_b = explode('|', $b);
if ($ex_a[1] == $ex_b[1]) {return 0;}
return ($ex_a[1] > $ex_b[1]) ? -1 : 1;
}
uasort($lines, 'sort_data_array');
$lines = array_values($lines);
foreach ($lines as $line_num => $dataset) {
//output
}
Use a custom sort function:
EG:
uasort ($lines, function($a , $b)) {
$ex_a = explode('|', $a);
$ex_b = explode('|', $b);
// change the < to > if they are in reverse...
return (strcmp($ex_a[1], $ex_b[1]) < 0 ? 1: -1);
}
print_r($lines);
Here is a method without a custom sort function.
This can be refactored if the number of columns is unknown.
<?php
$raw_records = 'Value_1|2|Value_3|Value_4|Value_5
Value_1|5|Value_3|Value_4|Value_5
Value_1|3|Value_3|Value_4|Value_5';
$records = array();
$lines = explode("\n", $raw_records);
foreach ($lines as $line_num => $dataset) {
$dataset = explode('|', $dataset);
$records[$dataset[1]][] = $dataset[0];
$records[$dataset[1]][] = $dataset[2];
$records[$dataset[1]][] = $dataset[3];
$records[$dataset[1]][] = $dataset[4];
}
ksort($records, SORT_NUMERIC);
echo '<pre>'; var_dump($records); echo '</pre>';
?>

Build array keys dynamically from another array

What is the best way to achieve the following? I.e. building the array keys from another array dynamically?
$array = (
'key1',
'key2',
'key3'
);
Resulting in:: $arr['key1']['key2']['key3'] = array()/value;
So in other words the more values you add to $array (and or less) then the corresponding mulitidensional array is built up.
Thanks
You could easily build a recursive function, or I use a reference:
$array = array('key1', 'key2', 'key3');
$result = array();
$temp = &$result;
foreach($array as $key) {
$temp =& $temp[$key];
}
$temp = 'value'; //or whatever
var_dump($result);
I'd already started, so I'll post my answer even though there's already an accepted answer:
$input = array('key1', 'key2', 'key3');
$result = array();
buildArray($input, $result);
print_r($result);
function buildArray($input, &$result){
if(0 == count($input))
return $result;
$next = array_shift($input);
$result[$next] = array();
buildArray($input, $result[$next]);
}
Works, though I think the answer posted by #AbraCadaver is more elegant.

return monodimensional-array from multidimensional

I have a multidimensional array:
$array=array( 0=>array('text'=>'text1','desc'=>'blablabla'),
1=>array('text'=>'text2','desc'=>'blablabla'),
2=>array('text'=>'blablabla','desc'=>'blablabla'));
Is there a function to return a monodimensional array based on the $text values?
Example:
monoarray($array);
//returns: array(0=>'text1',1=>'text2',2=>'blablabla');
Maybe a built-in function?
This will return array with first values in inner arrays:
$ar = array_map('array_shift', $array);
For last values this will do:
$ar = array_map('array_pop', $array);
If you want to take another element from inner array's, you must wrote your own function (PHP 5.3 attitude):
$ar = array_map(function($a) {
return $a[(key you want to return)];
}, $array);
Do it like this:
function GetItOut($multiarray, $FindKey)
{
$result = array();
foreach($multiarray as $MultiKey => $array)
$result[$MultiKey] = $array[$FindKey];
return $result;
}
$Result = GetItOut($multiarray, 'text');
print_r($Result);
Easiest way is to define your own function, with a foreach loop. You could probably use one of the numerous php array functions, but it's probably not worth your time.
The foreach loop would look something like:
function monoarray($myArray) {
$output = array();
foreach($myArray as $key=>$value) {
if( $key == 'text' ) {
$output[] = $value;
}
}
return $output;
}
If the order of your keys never changes (i.e.: text is always the first one), you can use:
$new_array = array_map('current', $array);
Otherwise, you can use:
$new_array = array_map(function($val) {
return $val['text'];
}, $array);
Or:
$new_array = array();
foreach ($array as $val) {
$new_array[] = $val['text'];
}
Try this:
function monoarray($array)
{
$result = array();
if (is_array($array) === true)
{
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value)
{
$result[] = $value;
}
}
return $result;
}
With PHP, you only have to use the function print_r();
So --> print_r($array);
Hope that will help you :D

Categories