php for and foreach loop only storing last value - php

I am looping though one initial array, and specifying values i want. Then i am storing the values i need in an array. Then i am combining those values into a new array, with keys and values. The new array is only storing the last entry of all the data that has been passed to it.
$exampleArray = array();
for ($i = 0; $i < 100; $i++){
$exampleArray[] = array(
$A1 = $Anotherarray[$i][25],
$A2 = $Anotherarray[$i][26],
$A3 = $Anotherarray[$i][24],
$A4 = $Anotherarray[$i][27],
$A5 = $Anotherarray[$i][28]
);
$secondExample = array();
foreach( $A1 as $i => $val )
{
$secondExample[] = array(
"Field1" => $val,
"Field2" => ucfirst($A2[$i]),
"Field3" => ucfirst($A3[$i]),
"Field4" => ucfirst($A4[$i]),
"Field5" => ucfirst($A5[$i])
);
}

You are declaring $secondExample as a new array on every iteration. Do it like this:
$exampleArray = array();
$secondExample = array();
for ($i = 0; $i < 100; $i++){
$exampleArray[] = array(
$A1 = $Anotherarray[$i][25],
$A2 = $Anotherarray[$i][26],
$A3 = $Anotherarray[$i][24],
$A4 = $Anotherarray[$i][27],
$A5 = $Anotherarray[$i][28]
);
$secondExample[$i] = array();
foreach( $A1 as $j => $val) {
$secondExample[$i][] = array(
"Field1" => $val,
"Field2" => ucfirst($A2[$j]),
"Field3" => ucfirst($A3[$j]),
"Field4" => ucfirst($A4[$j]),
"Field5" => ucfirst($A5[$j])
);
}

As because you are overwriting every time the loop goes.Use array_push
$secondExample = array();
foreach( $A1 as $i => $val )
{
$varArray = array(
"Field1" => $val,
"Field2" => ucfirst($A2[$i]),
"Field3" => ucfirst($A3[$i]),
"Field4" => ucfirst($A4[$i]),
"Field5" => ucfirst($A5[$i])
);
array_push($secondExample, $varArray);
}

Related

define array variable inside array

How to define variable inside array without key? This doesnt working and I dont know how...
$array = array("list" => array());
$list = $array["list"][] = array("sub_list" = array());
$list["sub_list"][] = "text1";
$list["sub_list"][] = "text2";
$list["sub_list"][] = "text2";
$list2 = $array["list"][] = array("sub_list" = array());
$list2["sub_list"][] = "text1";
$list2["sub_list"][] = "text2";
$list2["sub_list"][] = "text3";
Needed result:
$array = array(
"list" => array(
array(
"sub_list" = array("text1", "text2", "text3")
),
array(
"sub_list" = array("text1", "text2", "text3")
)
)
);
It's not used in loop or for/foreach!
$array = [
'list' => []
];
$list = [];
$list[] = 'text1';
$list[] = 'text2';
$list[] = 'text3';
$array['list'][]['sub_list'] = $list;
$array['list'][]['sub_list'] = $list;
$list = [];
$list[] = 'text4';
$list[] = 'text5';
$list[] = 'text6';
$array['list'][]['sub_list'] = $list;
And you will have :
$array = array(
"list" => array(
array(
"sub_list" => array("text1", "text2", "text3")
),
array(
"sub_list" => array("text1", "text2", "text3")
),
array(
"sub_list" => array("text4", "text5", "text6")
)
)
);
$array["list"][] = array("sub_list" => array());
$list= [];
$list[] = array("text1", "text2", "text3");
$list[] = array("text1", "text2", "text3");
$array["list"][]["sub_list"] = $list;
althought it's array inside array and this array is also in array
i need $array["list"][] as variable, when is called $array["list"][]["sub_list"] = $list; is created new one array, i need add "sub_list" to first array

How to merge multiple arrays in Codeigniter

I am trying to merge two arrays, but getting NULL. Below is my code
$a = 1;
foreach($codes as $values) {
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$this->data['output' . $a++] = $this->my_modal->simple_post($post_data);
}
$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);
var_dump($this->data['output']);
Any suggestions will be appreciated. Thanks..
You have to delete the first parameter (NULL) of array_merge();
And what is $this->input->$id? Don't you mean $id?
And in this environment, it's better to use array_push();:
$a = 1;
$this->data['output'] = array();
foreach($codes as $values)
{
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$new_data = $this->my_modal->simple_post($post_data);
array_push($this->data['output'], $new_data);
}
var_dump($this->data['output']);
$a = 1;
$this->data['output'] = array();
foreach($codes as $values){
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$data['output2']= $this->my_modal->simple_post($post_data);
if(count($this->data['output1']) > 1) {
$this->data['all'] = array_merge($this->data['output1'],$data['output2']);
}else {
$this->data['all'] = $data['output1'];
}
}
print_r($this->data['all']);
Your code is perfectly right, the only problem is that you start the counter with $a = 1, and do $a++ which will result in 2. So the output1 does not exist. However if you write (notice the subtle change):
$a = 1;
foreach($codes as $values) {
$id = $values['id'];
$post_data = array (
"id" => $id,
"name" => $this->input->post('Name'),
"from_date" => $this->input->post('FromDate'),
"to_date" => $this->input->post('ToDate')
);
$this->data['output' . $a] = $this->my_modal->simple_post($post_data); // $a = 1 now
$a++; // $a becomes 2 here
}
$this->data['output'] = array_merge($this->data['output1'], $this->data['output2']);
var_dump($this->data['output']);

Create an array with dynamic input in PHP

I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them
Format will be like-
{
"TEST1":{
"140724":[
{
"A":"1107",
"B":4444,
"C":"1129",
"D":"1129"
},
{
"A":"1010",
"B":2589,
"C":"1040",
"D":"1040"
}
],
"140725":[
]
}
}
So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.
$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
array_push($json_created,array($key = array()));
}
The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.
So my main point is to develop that logic so that irrespective the
number of inputs , my array formation must be intact.
You can use json_encode with array to do so
$array = array(
"TEST1" => array(
"140724" => array(
array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
),
array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
)
),
"140725" => array(
)
)
);
echo json_encode($array);
Another way to construct array is
$array = array();
$array["TEST1"]["140724"][] = array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
);
$array["TEST1"]["140724"][] = array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
);
$array["TEST1"]["140725"] = array();
echo json_encode($array);
Finally managed to write the code-
$keys_content = array("starttime", "id", "duration", "endtime");
$dates = array();//140724,140725,140726140727
$mainID =“TEST1”;
$arraySuperMain = array();
$arrayMain = array();
for ($j = 0; $j < count($dates); $j++) {
$array_main = array();
$subset = array();
for ($i = 0; $i < count($keys_content); $i++) {
$key = $keys_content[$i];
$subset = array_push_assoc($subset, $key, "Value".$i);
}
$array_main = array_push_assoc($array_main, $dates[$j], $subset);
array_push($arrayMain, $array_main);
}
$createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
public static function array_push_assoc($array, $key, $value) {
$array[$key] = $value;
return $array;
}

PHP: create array from arrays

I have a form that is posting 4 arrays that I need to combine and eventually compose to email. The four arrays:
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
will all have the same array length and each index will be related. How do I combine the 4 arrays such as
[0]
'qty' => '1',
'dimenesion => '2x2',
'thickness' => '2in',
'description' => 'this is the description'
[1]
'qty' => '1',
'dimenesion => '2x2',
'thickness' => '2in',
'description' => 'this is the description'
I have tried array_combined, array_merged and can't get the results that I am looking for. Thanks for the help on this.
If you have same length for those arrays here is example code:
$resultArray = array();
foreach($quantityArray as $index => $qty) {
$resultArray[$index]['qty'] = $qty;
$resultArray[$index]['dimenesion'] = $dimensionArray[$index];
$resultArray[$index]['thickness'] = $thicknessArray[$index];
$resultArray[$index]['description'] = $descriptionArray [$index];
}
print_r($resultArray);
This also may work:
<?php
//...
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
//
// combine them:
//
$combined = array();
$n = count($quantityArray);
for($i = 0; $i < $n; $i++)
{
$combined[] = array(
'qty' => $quantityArray[$i],
'dimenesion' => $dimensionArray[$i],
'thickness' => $thicknessArray[$i],
'description' => $descriptionArray[$i]
);
}
//
echo "<pre>";
print_r($combined);
echo "</pre>";
?>
If we assume that we have same length for those arrays here is my codes:
$quantityArray = array(1, 1, 5, 3);
$dimensionArray = array("2x2", "3x3", "4x4", "2x2");
$thicknessArray = array("2in", "3in", "4in", "2in");
$descriptionArray = array("this is the description 1", "this is the description 2 ", "this is the description3 ", "this is the description4" );
$myCombinArray = array();
foreach ( $quantityArray as $idx => $val ) {
$subArray = array (
'qty' => $quantityArray [$idx],
'dimenesion' => $dimensionArray [$idx],
'thickness' => $thicknessArray [$idx],
'description' => $descriptionArray [$idx]
);
array_push ( $myCombinArray, $subArray );
}
print_r($myCombinArray);
How about an easy way if there are always those 4 arrays:
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
$combinedArray = [$quantityArray, $dimensionArray, $thicknessArray, $descriptionArray];
# old syntax:
# $combinedArray = array($quantityArray, $dimensionArray, $thicknessArray, $descriptionArray);

PHP multiple arrays to one associative array

How can I merge this three arrays
$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};
into one multidimensional associative array in two different ways?
One way is the key order should be same as that of array "name".
$name_merged_original_order = array (
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
"John" => Array(
"v1" => "N/A",
"v2" => 500
),
"David" => Array(
"v1" => 100,
"v2" => "N/A"
)
)
Another ways is the alphabetical of array "name":
$name_merged_asc = array (
"David" => Array(
"v1" => 100,
"v2" => "N/A"
),
"John" => Array(
"v1" => "N/A",
"v2" => 200
),
"Tom" => Array(
"v1" => 100,
"v2" => 400
),
)
The tricky part is that array "v1" and "v2" is not ordered as the key of "name." They also don't have all keys as in "name." Thanks!
It's not tested and the easiest solution:
$name_merged_original_order = array();
foreach($name as $key){
$name_merged_original_order[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_original_order[$key]['v1'] = $v1[$key];
}
else{
$name_merged_original_order[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_original_order[$key]['v2'] = $v2[$key];
}
else{
$name_merged_original_order[$key]['v2'] = 'N/A';
}
}
sort($name);
$name_merged_asc = array();
foreach($name as $key){
$name_merged_asc[$key] = array();
if(array_key_exists($key, $v1)){
$name_merged_asc[$key]['v1'] = $v1[$key];
}
else{
$name_merged_asc[$key]['v1'] = 'N/A';
}
if(array_key_exists($key, $v2)){
$name_merged_asc[$key]['v2'] = $v2[$key];
}
else{
$name_merged_asc[$key]['v2'] = 'N/A';
}
}
As I understand you would like something like that:
$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
$result[$n] = array();
foreach($vars as $v)
{
if(array_key_exists($n, ${$v}))
$result[$n][$v] = ${$v}[$n];
}
}
I hope $result is what you need.
For Example, you have these arrays:
<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');
1)
foreach($FirstArrays as $index => $value) {
echo $FirstArrays[$index].$SecArrays[$index];
echo "<br/>";
}
or 2)
for ($index = 0 ; $index < count($FirstArrays); $index ++) {
echo $FirstArrays[$index] . $SecArrays[$index];
echo "<br/>";
}
Assume from your comments you only want items that match in all 3 arrays:
for( $i=0; $i< count($name) ; $i++){
if( !empty( $v1[ $name[$i]]) && !empty( $v2[ $name[$i]]) ){
$newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
}
}
To sort:
asort($newArray);

Categories