How to merge multiple arrays in Codeigniter - php

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']);

Related

ForEach loop inside associative array PHP

I have following foreach loop
$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$output1 = $idstand++;
echo "<li>product_id_$output1 = $item,</li>";
}
I want to add the output of the above loop inside following associative array
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge
)
So that the final array will look like this;
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge,
'product1_id' => 1255,
'product2_id' => 1256,
'product3_id' => 1257,
)
I tried creating following solution but its not working for me
$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$idoutput1 = $idstand++;
$paramas [] = array (
'product$idoutput1_id' => $item,
);
}
Need advice.
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...
$paramas['product' . $idoutput1 . '_id'] = $item;

php for and foreach loop only storing last value

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);
}

PHP foreach returning last row in multidimentional array

I am trying get user value from multidimensional array as
$array = array();
$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";
$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";
$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";
$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";
foreach($array as $e){
print_r($e);
}
It return me 4name4country4 only
I need to fetch rows like
foreach($array as $e){
$id=$e['id'];
$name=$e['name'];
$country=$e['country'];
echo $id.'/'.$name.'/'.$country.'<br>';
}
but this gives me error as Illegal string offset 'id'
from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it
Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";
$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";
OR
$array = array(
0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);
Instead, do it like so you won't have to give array keys manually
$array = array();
$array[] = array("id" => 123, "name" => "Your name", "country" => "UK");
$array[] = array("id" => 1342, "name" => "Your name 2 ", "country" => "UK");
then in foreach do this
foreach($array as $key => $val){
echo $key. ": ".$val['id']. " " . $val['name'];
}
You have to create the multidimensional array like this, right now you're overwriting the array multiple times.
$arrays = [
[0]=>
["id"] => "1",
["name"] => "name1",
["country"] => "country1"
],
[1]=>[
...
]
];
foreach($arrays as $array){
$id=$array['id'];
$name=$array['name'];
$country=$array['country'];
echo $id.'/'.$name.'/'.'$country'.'<br>';
}

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);

Dynamic array key in while loop

I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}

Categories