I've two dynamic arrays very basic format, each contain related information one another but the output fo the array is separately
First array are "id's"
Array
(
[0] => 190
[1] => 189
)
Second array are "quantities"
Array
(
[0] => 3
[1] => 5
)
The final step is to build those two arrays in to this array:
Array
(
[0] => Array
(
[id] => 190
[qu] => 3
)
[1] => Array
(
[id] => 189
[qu] => 5
)
)
The API I'm using has 2 outputs/files for different purposes on the first output are ID's and second Output are "quantities"(I have no idea why they do it like that)... but the thing is that now I have the arrays I need to put them together like that...
using array_merge(); only makes a single array in list which is not working for what I need...
This is what merge those
Array
(
[0] => 190
[1] => 189
[2] => 3
[3] => 5
)
that is not going to fly...
So how can I build that array? Thank you.
<?php
$id = array(
"190",
"189",
);
$quantities = array(
"3",
"5",
);
$finished = array();
foreach($id as $key=>$item) {
array_push($finished, array($item, $quantities[$key]));
}
print_r($finished);
Assuming the keys in the two arrays are identical;
$arr = array();
$ids = array('189', '190');
$quantities = array('3', '5');
foreach ($ids as $key => $id) {
$arr[$key] = array('id' => $id, 'qu' => $quantities[$key]);
}
Related
This question already has answers here:
Transpose a PHP multidimensional array with predefined keys
(3 answers)
How to transpose a multidimensional multi-file upload submission and maintain associative keys?
(4 answers)
Closed 1 year ago.
i have an array that i get from a form with alot of fields, i need to order those fields under an array and that array under the ''main'' array. Ill post what i have, and what i need to get.
WHAT I HAVE:
Array
(
[perfil_area1] => Array
(
[0] => a2
[1] => a3
)
[perfil_years] => Array
(
[0] => 2
[1] => 4
)
[perfil_function] => Array
(
[0] => f1
[1] => f4
)
[perfil_obs] => Array
(
[0] => teste1
[1] => teste2
)
[perfil_company] => Array
(
[0] => emp1
[1] => emp2
)
)
This is what i need to be so i can turn it into a query:
What i need
Array
(
[0] =>
(
[perfil_area1] => a2
[perfil_years] => 2
[perfil_function] => f1
[perfil_obs] => teste1
[perfil_company] => emp1
)
[1] =>
(
[perfil_area1] => emp2
[perfil_years] => 2
[perfil_function] => f4
[perfil_obs] => 4
[perfil_company] => a3
)
)
i have tried with 2 foreach but i didnt manage to get it done. I have read Create a multidimensional array in a loop , how to create multidimensional array using a foreach loop in php? , create multidimensional array using a foreach loop , Converting an array from one to multi-dimensional based on parent ID values and some more but i still cant do it. Any tips on how to create it?
You just need to loop over the input array and build the new array
$new = [];
foreach ($in as $key=>$arr) {
$new[0][$key] = $arr[0];
$new[1][$key] = $arr[1];
}
<?php
$result = [];
for ($i=0; $i<count(reset($array)); $i++) {
$result[] = array_combine(array_keys($array), array_column($array, $i));
}
Please read the manual for more details about array_combine(), array_keys() and array_column().
I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587
This question already has answers here:
PHP array replace numbers with keys
(2 answers)
Closed 6 years ago.
When doing a print_r on my array, I get the following output;
Array
(
[0] => Array
(
[id] => 178
[name] => Briar Price
)
[1] => Array
(
[id] => 90
[name] => Bradley Kramer
)
[2] => Array
(
[id] => 508
[name] => Calvin Yang
)
[3] => Array
(
[id] => 457
[name] => Charles Valenzuela
)
... and so on
How can I modify the array to look like this;
Array
(
[178] => Briar Price
[90] => Bradley Kramer
[508] => Calvin Yang
[457] => Charles Valenzuela
... and so on
)
I just want to make the ID the key for the value name. I always have issues when it comes to arrays reordering.
Pass third parameter to array_column to make its key as
$array = array_column($users, 'name', 'id');
print_r($array);
Use foreach() -
$newArr = array();
foreach ($your_array as $key => $val) {
$newArr[$val['id']] = $val['name'];
}
print_r($newArr) // desired output
I'd use array_combine which attaches new keys to values
$results = [
['id'=>1,'name'=>'John'],['id'=>2,'name'=>'Jane'],
];
$results = array_combine(
array_column($results,'id'), //use 'id' column as keys
array_column($results,'name') //use 'name' column as values
);
//now $results is [1=>'John', 2=>'Jane']
You can do it using array_column and array_combine PHP function without applying custom logic.
Here is how you do it,
<?php
$keys=array_column($mainarray,'id');
$values=array_column($mainarray,'name');
$finalarray=array_combine($keys,$values);
$finalarray will be your desired result.
array_combine creates an array by using one array for keys and another for its values.
array_column returns the values from a single column in the input array.
I have a big problem and I can't resolve it,
So I have my array :
Array
(
[0] => Array
(
[id] => 34
[groupe_id] => 4
[object_id] => 4
)
[1] => Array
(
[id] => 35
[groupe_id] => 4
[object_id] => 5
)
)
Now I want to create another array call $test for get the array in this forme:
Array
(
[object_id] = 4
[object_id] = 5
)
I tried but no results:
$test = array();
foreach($aObjectsGroupe as $object){
$test[] = array(
'object_id' => $object['object_id']
);
}
You can't have duplicates of the same key in a PHP array. It kind of defeats the purpose of keys. I can't think of a reason to have identical keys, as you would be unable to reference an individual element of the array by key anyways, because there are more than one.
Why not just make an array called $object_ids, and just have a normal indexed array of the all of the object_ids from the other array?
$object_ids = array();
foreach ($aObjectsGroupe as $object) {
$object_ids[] = $object['object_id'];
}
I'm trying to access multiple values in multiple foreach loops outside of the loops:
foreach(array1 as arr1) {
$var1 = arr2['value1']; //$array is associative array with mutliple keys value1
}
Then I have another
foreach(array2 as arr2) {
$var2 = arr2['value']; //$array2 is another associative array with multiple keys value
}
All of this is within another big foreach loop and now I want to create an array within the big foreach with $var1 and $var2 being used. This array I'm going to be creating is going to be an associative array as well. Any ideas how I can do this?
Array 1:
Array
(
[0] => Array
(
[id] => 1
[id_name] => 251452
[name] => bob
)
[1] => Array
(
[id] => 2
[id_name] => 251453
[name] => bob
)
)
Array 2:
Array
(
[0] => Array
(
[id_person] => 4
[id_last_name] => 251452
[last_name] => smith
)
[1] => Array
(
[id_person] => 15
[id_last_name] => 251453
[last_name] => johnson
)
)
Assume these come from two different queries from the database.
I want to get the first name from the first array for each one and get the last name from the second array for each one and make one array that has this data along with others.
Have a look into multi dimensional arrays.
Also have a look at stdclass and maybe creating an array of these which can store many variables within a single definition - which can help in many ways. (standard class)
Nested looping - this would just dump all sub arrays into an object
// Object and array examples for an InnerArray
$Object = new stdclass();
$AllOfIt = array();
$cnt = 0;
foreach($OuterArray as $OuterKey => $InnerArray)
{
$cnt++;
foreach($InnerArray as $InnerKey => $InnerValue)
{
$Object->$cnt = $InnerValue;
$AllOfIt[$cnt] = $InnerValue;
}
}