New array from Multiple foreach loops - php

I am trying to create an array out of three arrays in the following manner:
$file_data = array();
foreach($file_ids as $key => $id){
foreach($file_names as $name_key => $name){
foreach($file_amounts as $file_key => $cost){
$file_data[] = array("id" => $id, "filename" => $name, "amount" => $cost);
break;
}
break;
}
}
It's creating the first row only. How can I get it to properly assign the values to the $file_data array?
Thanks.
UPDATE:
As an example, I have the following for the three arrays
$file_ids[0] = 2;
$file_ids[1] = 4;
$file_name[0] = name1;
$file_name[1] = name2;
$file_amount[0] = 10;
$file_amount[1] = 9;
These arrays will always be of the same size.
What I would like to do is iterate over these arrays and end up with a final array of the form:
$final_array = (id, name, amount)
for all rows in other arrays.

These arrays will always be of the same size.
Just loop to the width of either array:
$final_array = array();
for($i = 0; $i < count($file_name); $i++)
{
$final_array[] = array($file_ids[$i],$file_name[$i],$file_amount[$i]);
}

Make use of array_map and array_combine:
$file_ids = array(2, 4);
$file_name = array('name1', 'name2');
$file_amount = array(10, 9);
$result = array_map(null, $file_ids, $file_name, $file_amount);
$keys = array('id', 'filename', 'ammount');
$result = array_map(function($el) use ($keys) {
return array_combine($keys, $el);
}, $result);
echo '<pre>'; print_r($result); echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 2
[filename] => name1
[ammount] => 10
)
[1] => Array
(
[id] => 4
[filename] => name2
[ammount] => 9
)
)

Only iterate over one array
$file_ids = array(2,4);
$file_name = array('name1', 'name2');
$file_amount = array(10,9);
$cnt = count($file_ids);
$file_data = array();
for($i = 0; $i < $cnt; $i++){
$file_data[] = array('id' => $file_ids[$i],
'filename' => $file_name[$i],
'amount' => $file_amount[$i]);
}
var_dump($file_data);

Related

Combine same indexes of array

I have an array which as dynamic nested indexes in e.g. I am just using 2 nested indexes.
Array
(
[0] => Array
(
[0] => 41373
[1] => 41371
[2] => 41369
[3] => 41370
)
[1] => Array
(
[0] => 41378
[1] => 41377
[2] => 41376
[3] => 41375
)
)
Now I want to create a single array like below. This will have 1st index of first array then 1st index of 2nd array, 2nd index of first array then 2nd index of 2nd array, and so on. See below
array(
[0] =>41373
[1] => 41378
[2] => 41371
[3] => 41377
[4] => 41369
[5] => 41376
[6] => 41370
[7] => 41375
)
You can do something like this:
$results = [];
$array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
$count = 1;
$size = count($array)-1;
foreach ($array[0] as $key => $value)
{
$results[] = $value;
while($count <= $size)
{
$results[] = $array[$count][$key];
$count++;
}
$count = 1;
}
I think you need something like this:
function dd(array $arrays): array
{
$bufferArray = [];
foreach($arrays as $array) {
$bufferArray = array_merge_recursive($bufferArray, $array);
}
return $bufferArray;
}
$array1 = ['41373','41371','41369','41370'];
$array2 = ['41378','41377', '41376', '41375'];
$return = array();
$count = count($array1)+count($array2);
for($i=0;$i<($count);$i++){
if($i%2==1){
array_push($return, array_shift($array1));
}
else {
array_push($return, array_shift($array2));
}
}
print_r($return);
first count the arrays in the given array, then count the elements in the first array, than loop over that. All arrays should have the same length, or the first one should be the longest.
$laArray = [
['41373','41371','41369','41370'],
['41378', '41377', '41376', '41375'],
['43378', '43377', '43376', '43375'],
];
$lnNested = count($laArray);
$lnElements = count($laArray[0]);
$laResult = [];
for($lnOuter = 0;$lnOuter < $lnElements; $lnOuter++) {
for($lnInner = 0; $lnInner < $lnNested; $lnInner++) {
if(isset($laArray[$lnInner][$lnOuter])) {
$laResult[] = $laArray[$lnInner][$lnOuter];
}
}
}
this would be the simplest solution:
$firstarr = ['41373','41371','41369','41370'];
$secondarr = ['41378','41377','41376','41375'];
$allcounged = count($firstarr)+count($secondarr);
$dividedintotwo = $allcounged/2;
$i = 0;
while ($i<$dividedintotwo) {
echo $firstarr[$i]."<br>";
echo $secondarr[$i]."<br>";
$i++;
}

Convert array to another character [php]

I have data in the form:
$data = Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 3 )
I want to convert it to:
$x = [[1], [2], [3], [4]];
I do not know how to do this?
I'm using the library PHP-ML ( http://php-ml.readthedocs.io/en/latest/machine-learning/regression/least-squares/ ).
If you want to create array from values, you can do it this way:
$x = [];
foreach($data as $key => $value) {
array_push($x, $value);
}
If you want to create array of arrays from values you can edit it like this:
$x = [];
foreach($data as $key => $value) {
array_push($x, [$value]);
}
$data = array(1,4,3,3);
$x = '[['.implode('], [', $data).']]';
echo $x;
$data = array(0 => "0", 1 => "1", 2 => "2", 3 => "3");
$output;
$halt = count($data) - 1;
for($i = 0; $i < count($data); $i++){
if($i==$halt){
$output.="[".$data[$i]."]";
}else{
$output.="[".$data[$i]."]".", ";
}
}
$x = "[".$output."]";
echo $x;
Like so?
But why change array to array?
Ahhh I see, You want it in a json format?*
$array = array( 0 => [1], 1 => [2] , 2 => [3], 3 => [3] );
$x = json_encode($array, JSON_HEX_APOS);
echo $x;
[[1],[2],[3],[3]]

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

How to convert an array into key-value pair array?

I am having this array :
array(
0 => array("name", "address", "city"),
1=> array( "anoop", "palasis", "Indore"),
2=> array( "ravinder", "annapurna", "Indore")
)
and i want to make this array in this way :
array(
0 => array("name" = >"anoop" , "address" = >"palasia", "city" = >"Indore"),
1 => array("name" = >"ravinder" , "address" = >"annapurna", "city" = >"Indore")
)
The modern way is:
$data = array_column($data, 'value', 'key');
In your case:
$data = array_column($data, 1, 0);
Use array_combine. If $array contains your data
$result = array(
array_combine($array[0], $array[1]),
array_combine($array[0], $array[2])
);
In general
$result = array();
$len = count($array);
for($i=1;$i<$len; $i++){
$result[] = array_combine($array[0], $array[$i]);
}
If your data are in $array:
$res = array();
foreach ($array as $key=>$value) {
if ($key == 0) {
continue;
}
for ($i = 0; $i < count($array[0]); $i++) {
$res[$array[0][$i]] = $value[$i];
}
}
The result is now in $res.
Here is a function that you can use:
function rewrap(Array $input){
$key_names = array_shift($input);
$output = Array();
foreach($input as $index => $inner_array){
$output[] = array_combine($key_names,$inner_array);
}
return $output;
}
Here is a demonstration:
// Include the function from above here
$start = array(
0 => array("name", "address", "city"),
1 => array("anoop", "palasis", "Indore"),
2 => array("ravinder", "annapurna", "Indore")
);
print_r(rewrap($start));
This outputs:
Array
(
[0] => Array
(
[name] => anoop
[address] => palasis
[city] => Indore
)
[1] => Array
(
[name] => ravinder
[address] => annapurna
[city] => Indore
)
)
Note: Your first array defined index 1 twice, so I changed the second one to 2, like this:
array(0 => array("name", "address", "city"), 1 => array("anoop", "palasis", "Indore"),2 => array("ravinder", "annapurna", "Indore"))
That was probably just a typo.
Assuming that you are parsing a CSV file, check out the answers to this question:
Get associative array from csv

php separate array label and values

i have arrays like this
Array(
[0] => Array(
[member_name] => hohoho
[member_type] => SUPPLIER
[interest] => Array(
[0] => HOLIDAY
[1] => MOVIES)
),
[1] => Array(
[member_name] => jajaja
[member_validity] => 13/12/2001
[interest] => Array(
[0] => SPORTS
[1] => FOODS)
)
)
how can I put the array keys and items in a separate variable? for example, i want to have something like
$keyholder[0] = member_name,member_type,interest
$keyholder[1] = member_name,member_validity,interest
$itemholder[0] = hohoho,SUPPLIER,{HOLIDAY,MOVIES}
$itemholder[1] = jajaja,13/12/2001,{SPORTS,FOODS}
Try array_keys() and array_values()
http://php.net/manual/en/function.array-keys.php
http://www.php.net/manual/en/function.array-values.php
You can cycle through an array and get the key and values like this:
foreach ($array as $key => $val)
{
echo $key." - ".$val."<br/>";
}
$keyholder=array();
$itemholder=array();
foreach($original_array as $values){
$inner_keys=array();
$inner_values=array();
foreach($values as $key=>$value){
$inner_keys[]=$key;
$inner_values[]=$value;
}
$keyholder[]=$inner_keys;
$itemholder[]=$inner_values;
}
I think this will do it:
$cnt = count($original);
$keys = array();
$items = array();
for($i = 0; $i < $cnt; $i++) {
$keys[] = array_keys($original[$i]);
$items[] = array_values($original[$i]);
}

Categories