multidimensional array from comma separated string - php

im trying to convert a comma separated into a multidimensional array to create a menu structure of this.
this is what i have already..
for ($i=0; $i < $count; $i++) {
if($i > 0){
array_push($tagmenu[0][$pretags[$i-1]], array($pretags[$i]=>array()));
} else {
array_push($tagmenu, array($pretags[$i]=>array()));
}
}
i have this as a string
$tags = 'image,landscape,night';
and i want it to look like this
Array(
[images] = Array (
[landscape] = Array(
[night] = Array ()
)
)
i'm searching my fingers off on this

$tags = 'image,landscape,night';
$newArray = array();
$wrkArray = &$newArray;
foreach(explode(',',$tags) as $tag) {
$wrkArray[$tag] = array();
$wrkArray = &$wrkArray[$tag];
}
unset($wrkArray);
var_dump($newArray);

Related

How to merge multiple arrays outside of their loops?

I am trying to create an array from 2 other arrays. I am having a problem getting them merged outside of their loops.
Here is the code to build the 2 arrays:
$redDogs = '3';
$blueDogs = '2';
$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
$reds[] = 'red_dog_' . $i++;
}
foreach ($reds as $red) {
print '<pre>'; print_r($red); print '</pre>';
}
$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
$blues[] = 'blue_dog_' . $j++;
}
foreach ($blues as $blue) {
print '<pre>'; print_r($blue); print '</pre>';
}
How could I create an array like:
print_r($alldogs);
To produce the following output:
Array {
[0] => red_dog_1
[1] => red_dog_2
[2] => red_dog_3
[3] => blue_dog_1
[4] => blue_dog_2
}
I have tried array_merge($red, $blue) but don't seem to get any values.
Any help is greatly appreciated.
$redDogs = '3';
$blueDogs = '2';
$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
$reds[] = 'red_dog_' . $i++;
}
$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
$blues[] = 'blue_dog_' . $j++;
}
print_r(array_merge($reds, $blues));
Merge your array before looping through the array.
Your foreach statements were converting your array to strings.

create array with key and value from string

I have a string:
$content = "test,something,other,things,data,example";
I want to create an array where the first item is the key and the second one the value.
It should look like this:
Array
(
[test] => something
[other] => things
[data] => example
)
How can I do that? It's difficult to search for a solution because I don't know how to search this.
It's very similar to this: Explode string into array with key and value
But I don't have a json array.
I tried something like that:
$content = "test,something,other,things,data,example";
$arr = explode(',', $content);
$counter = 1;
$result = array();
foreach($arr as $item) {
if($counter % 2 == 0) {
$result[$temp] = $item;
unset($temp);
$counter++;
} else {
$temp = $item;
$counter++;
continue;
}
}
print_r($result);
But it's a dirty solution. Is there any better way?
Try this:
$array = explode(',',$content);
$size = count($array);
for($i=0; $i<$size; $i++)
$result[$array[$i]] = $array[++$i];
Try this:
$content = "test,something,other,things,data,example";
$data = explode(",", $content);// Split the string into an array
$result = Array();
$size = count($data); // Calculate the size once for later use
if($size%2 == 0)// check if we have even number of items(we have pairs)
for($i = 0; $i<$size;$i=$i+2){// Use calculated size here, because value is evaluated on every iteration
$result[$data[$i]] = $data[$i+1];
}
var_dump($result);
Try this
$content = "test,something,other,things,data,example";
$firstArray = explode(',',$content);
print_r($firstArray);
$final = array();
for($i=0; $i<count($firstArray); $i++)
{
if($i % 2 == 0)
{
$final[$firstArray[$i]] = $firstArray[$i+1];
}
}
print_r($final);
$content = "test,something,other,things,data,example";
$x = explode(',', $content);
$z = array();
for ($i=0 ; $i<count($x); $i+=2){
$res[$x[$i]] = $x[$i+1];
$z=array_merge($z,$res);
}
print_r($z);
I have tried this example this is working file.
Code:-
<?php
$string = "test,something|other,things|data,example";
$finalArray = array();
$asArr = explode( '|', $string );
foreach( $asArr as $val ){
$tmp = explode( ',', $val );
$finalArray[ $tmp[0] ] = $tmp[1];
}
echo "After Sorting".'<pre>';
print_r( $finalArray );
echo '</pre>';
?>
Output:-
Array
(
[test] => something
[other] => things
[data] => example
)
For your reference check this Click Here
Hope this helps.
You could able to use the following:
$key_pair = array();
$arr = explode(',', $content);
$arr_length = count($arr);
if($arr_length%2 == 0)
{
for($i = 0; $i < $arr_length; $i = $i+2)
{
$key_pair[$arr[$i]] = $arr[$i+1];
}
}
print_r($key_pair);
$content = "test,something,other,things,data,example";
$contentArray = explode(',',$content);
for($i=0; $i<count($contentArray); $i++){
$contentResult[$contentArray[$i]] = $contentArray[++$i];
}
print_r( $contentResult);
Output
Array
(
[test] => something
[other] => things
[data] => example
)
$contentResult[$contentArray[1]] = $contentArray[2];
$contentResult[$contentArray[3]] = $contentArray[4];
$contentResult[$contentArray[5]] = $contentArray[6];

How to extract adjacent pair of words in associative array in php?

I have an associative array in PHP like this:
$weight["a"]=1;
$weight["b"]=4;
$weight["c"]=5;
$weight["d"]=9;
Here I want to calculate pair-wise difference between consecutive array elements, e.g.,
"b-a" = 3
"c-b" = 1
"d-c" = 4
How should this be computed?
Try this:
$i = 0;
foreach ($weight AS $curr) {
if ($i > 0) {
echo '"'.array_keys($weight)[$i].'-'.array_keys($weight)[$i-1].'" = '.($curr-$prev)."<br />";
}
$i++;
$prev = $curr;
}
Store keys on a temporary array where keys are integers on which you can easily get the next key, and use it to parse your main array.
$tmp_array = array();
foreach ($weight as $key => $val) {
$tmp_array[] = $key;
}
$array_length = count($tmp_array);
for ($i = 0; i < array_length - 2; ++$i) {
echo $weight[$tmp_array[$i+1]], '-', $weight[$tmp_array[$i]], ' = ', ($weight[$tmp_array[$i+1]] - $weight[$tmp_array[$i]], PHP_EOL;
}

PHP: Loop through a multidimesional PHP array

I've got an array of 'contestant entrants' which can be shown like this:
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
...
)
From these entries I need to create another array called $draw.
The $draw array will have username repeated as many times as it's corresponding number_of_entries. So for the above example it might look like this:
$draw = array("122", "123", "123", "123", "123", "124", "124", "124")
I want this so that I can later generate a random number, and find the winner by doing something like $draw[$randomNumber];
However I cannot get my head around how to create that $draw array from the $all_entrants array... Any help will be greatly appreciated!
I assume you're looking for something like this?
$draw = array();
foreach($all_entrants as $entrant) // loop through array with entrants
for ($i = 0; $i<$entrant['number_of_entries']; $i++) //get number of entries
$draw[] = $entrant['username']; //add them to the $draw array
I think it's a question about select one from a group of name which has different weight.
maybe an array like this
$group = array(
array('122' => 1),
array('123'=> 4),
array('124'=> 3)
);
First Calculate the sum of the weight, or may be it has been known already
$total_weight = 0;
foreach($group as $weight){
$total_weight += $weight;
}
Then generate a random number from 0 to $total_weight, eg. 0<=$rand_number
$current_total = 0;
foreach($group as $name => $weight){
if($rand_number <= $current_total)
return $name;
$current_total += $weight;
}
--
BTW, I'm new here, more to learn:)
<?php
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
);
$draw = array();
foreach($all_entrants as $entrant) {
$draw = array_merge(
$draw,
array_fill(0, $entrant['number_of_entries'], $entrant['username'])
);
}
var_dump($draw);
Try this
$newarray=array();
foreach($all_entrants as $list){
for($i=1;$i<=$list['number_of_entries'];$i++){
array_push($newarray,$list['username']);
}
}
<?php
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
$draw = array();
for ($i = 0; $i < count($all_entrants); $i++)
{
$entrants = $all_entrants[$i];
$name = $entrants["username"];
$entry_count = $entrants["number_of_entries"];
for ($j = 0; $j < $entry_count; $j++) $draw[] = $name;
}
print_r($draw);
?>
Hope it helps.
check this :--
$result=array();
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
foreach($all_entrants as $value)
for($i=0;$i<$value['number_of_entries'];$i++)
array_push($result,$value['username']);
echo '<pre>';
print_r($result);
output :-
Array
(
[0] => 122
[1] => 123
[2] => 123
[3] => 123
[4] => 123
[5] => 124
[6] => 124
[7] => 124
)

PHP Array explode single value

I have an array with a single value collected from database.
Within a while loop I wish to explode this for every two values.
Example:
$data = array('20;40;60;80;100;150;200;300;500;1000');
I want to explode this value and end up with the following loop:
$lowprice = "20";
$highprice = "40";
I couldn't find any examples of this.
Many thanks everyone who answered!
You can use preg_match_all().
Example:
$text = '20;40;60;80;100;150;200;300;500;1000';
preg_match_all("/([^;]+);([^;]+)/", $text, $pairs, PREG_SET_ORDER);
foreach ($pairs as $pair) {
// ...
$lowvalue = $pair[1];
$highvalue = $pair[2];
// ...
}
If you really must use explode and a while loop, the following will also work:
$text = '20;40;60;80;100;150;200;300;500;1000';
$data = explode(';', $text);
$i = 0;
$count = count($data);
while ($i < $count) {
// ...
$lowvalue = $data[$i++];
$highvalue = $data[$i++];
// ...
}
If you just want the first and second values as your low/high:
$data = array('20;40;60;80;100;150;200;300;500;1000');
list($lowprice,$highprice) = explode(';',current($data));
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
If you want an array of lows and highs:
$data = array('20;40;60;80;100;150;200;300;500;1000');
$lowprices = $highprices = array();
$data = explode(';',current($data));
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
EDIT
Why not start out with a proper array of values in the first place: it would simplify this a lot
$data = array(20,40,60,80,100,150,200,300,500,1000);
list($lowprice,$highprice) = $data;
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
or
$data = array(20,40,60,80,100,150,200,300,500,1000);
$lowprices = $highprices = array();
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
Explode initially on the ;. Then in a for loop incrementing by 2, you can assign the current and next values to a sub-array:
$initarray = explode(";", "20;40;60;80;100;150;200;300;500;1000");
$num = count($initarray);
// Main array to hold subarrays
$outputarray = array();
for ($i=0; $i<$num; $i=$i+2) {
// Add the current pair ($i and $i+1) to a sub-array
$outputarray[] = array("lowprice"=>$initarray[$i], "highprice"=>$initarray[$i+1]);
}
Outputs:
Array
(
[0] => Array
(
[lowprice] => 20
[highprice] => 40
)
[1] => Array
(
[lowprice] => 60
[highprice] => 80
)
[2] => Array
(
[lowprice] => 100
[highprice] => 150
)
[3] => Array
(
[lowprice] => 200
[highprice] => 300
)
[4] => Array
(
[lowprice] => 500
[highprice] => 1000
)
)
You may use loop like this one (using explode() and array_shift()):
$data = explode( ';', '20;40;60;80;100;150;200;300;500;1000');
while( count( $data) > 1){
$lowprice = array_shift( $data);
$highprice = array_shift( $data);
}
Or use for loop (should be more effective than calling count() in every iteration):
$count = count( $data);
for( $i = 0; $i < $count; $i+=2){}

Categories