How to add new index and value from another array in PHP? - php

I need your help with my problem. My problem is I have 2 arrays the first one is the main array. The second is the array for my new data.
Let's say I have these arrays.
This is the main array:
Array
(
0 => Array
(
'id' => 1,
'name' => 'Apple',
'age' => 12
)
1 => Array
(
'id' => 2,
'name' => May,
'age' => 13
)
)
This is the second array:
Array
(
1 => Array
(
'gender' => 'Male'
)
2 => Array
(
'gender' => 'Female'
)
)
And I have this loop in PHP
foreach($main_array as &$main){
//this is the loop inside the first array
// how can I add the second array with it?
}
This is the sample output:
[0] => Array
(
[id] => 1
[name] => Apple
[age] => 12
[gender] => Female
)
[1] => Array
(
[id] => 2
[name] => May
[age] => 13
[gender] => Female
)
How can I do that? Any suggestions? That's all thanks.

for($i=0; $i<count($main_array); $i++){
for($j=0; $j<count($second_array); $j++){
if($main_array[$i]['id'] == $j){
$main_array[$i]['gender'] = $second_array[$j]['gender']
}
}
}

I fixed your example code, it wont run otherwise.
<?php
// Test data:
$main_array = Array(
0 => Array(
'id' => 1,
'name' => 'Apple',
'age' => 12
),
1 => Array (
'id' => 2,
'name' => 'May',
'age' => 13
)
);
$lookup = Array(
1 => Array(
'gender' => 'Male'
),
2 => Array(
'gender' => 'Female'
)
);
// Your answer:
foreach ($main_array as &$main) {
if (array_key_exists($main['id'],$lookup)) {
$main['gender'] = $lookup[$main['id']]['gender']; // <-- sets gender value
}
}
// Output it to browser:
echo '<pre>$main_array = '.print_r($main_array,true).'</pre>';
The array_key_exists() check is there to avoid errors such as PHP Notice: Undefined offset: 123 when the $lookup data is incomplete.

If you want to merge all of the data from both arrays:
PHP tools:
The exact behaviors of these functions needs to be studied and tested before usage, to make sure it fits your intent.
// array merge recursive doesn't merge numeric keys
$main_array = array_merge_recursive($main_array, $secondary_array);
// array replace recursive has a downside of replacing stuff
$main_array = array_replace_recursive($main_array, $secondary_array);
Rolling your own:
foreach($main_array as $i => &$main){
if(isset($secondary_array[$i])) {
foreach($secondary_array[$i] AS $key => $value) {
$main[$key] = $value;
}
}
}
Both of the above solutions only apply if the array-indexes of $main_array and $secondary_array match.
In your example your arrays don't match:
- $secondary_array[0] doesn't exist so $main_array[0] will not be populated with a 'gender' value;
- $main_array[2] doesn't exist so $main_array[2] will be created and it will only have a 'gender' value same as $secondary_array[2]['gender']
If you want to only merge some bits and pieces of the arrays:
Rolling your own:
foreach($main_array as $i => &$main) {
if(isset($secondary_array[$i])) and isset($secondary_array[$i]['gender'])) {
$main['gender'] = $secondary_array[$i]['gender'];
}
}

foreach($main_array as &$main){//this is the loop inside the first array
foreach($second_array as &$second){ //this is the loop inside the second array
}
}

foreach($arr1 as $k => $arr1Item) {
$arr1[$k]['gender'] = $arr2[$k]['gender'];
}

Related

Finding value from another one in an array of arrays

I got the follwing array and I would like to retrieve the name by the id:
Array
(
[0] => Array
(
[id] => 1
[name] => john
)
[1] => Array
(
[id] => 2
[name] => mark
)
etc...
It is doable with double foreach loop and a conditional test, but is there a more elegant way?
Assuming that id is unique...
Long Version
$arr = [
['id'=1, 'name'='john'],
['id'=2, 'name'='mark'],
];
$lookup = [];
foreach($arr as $row) {
$id = $row['id'];
$name = $row['name'];
$lookup[$id] = $name;
}
// find name for id, 2
echo $lookup[2];
// ==> mark
Short Version
...see Progrock’s solution!
You can use array_column to map ids to names:
<?php
$arr = [
['id' => 1, 'name' => 'Rolf'],
['id' => 3, 'name' => 'Gary'],
['id' => 2, 'name' => 'Jimmy'],
];
$id_names = array_column($arr, 'name', 'id');
var_export($id_names);
print $id_names[3];
Output:
array (
1 => 'Rolf',
3 => 'Gary',
2 => 'Jimmy',
)Gary

PHP recreate array if it contains certain values

I have $fruits_arr:
Array
(
[0] => Array
(
[id] => 213
[fruit] => banana
)
[1] => Array
(
[id] => 438
[fruit] => apple
)
[2] => Array
(
[id] => 154
[fruit] => peach
)
)
And $ids_arr:
Array (
[0] => 213
[1] => 154
)
I want to recreate $fruits_arr to have only array items where id is equal to a value from $ids_arr. I also want to maintain the index/array order of $fruits_arr.
I'm using the following:
$selected_fruits = array();
foreach( $fruits_arr as $fruit ) :
if ( in_array( $fruit['id'], $ids_arr ) ) :
$selected_fruits[] = $fruit;
endif;
endforeach;
print_r( $selected_fruits );
It seems to work but I am wondering if there is a shorter, better way to accomplish this in the latest PHP version.
This is not a shorter or newer way, but perhaps instead of performing in_array for every iteration, you could use array_flip and then use isset to check for the key:
$ids_arr = array_flip($ids_arr);
$selected_fruits = [];
foreach ($fruits_arr as $k => $fruit) {
if (isset($ids_arr[$fruit["id"]])) {
$selected_fruits[$k] = $fruit;
}
}
Php demo
You could use array_filter to make it more concise, but it will not be much and could make your code less readable. If possible chose readability over length of code.
$selected_fruits = array_filter($fruits_arr, function ($el) use ($ids_arr) {
return in_array($el['id'], $ids_arr, true);
});
or you can wait for PHP 7.4 (due to come out at the end of the year) and use arrow functions.
$selected_fruits = array_filter($fruits_arr, fn ($el) => in_array($el['id'], $ids_arr, true));
Demo: https://3v4l.org/4UC41
If the array is associative (use array_column for that) then you can use array_intersect_key to do the job.
$fruits_arr = array_column($fruits_arr, Null, "id");
$result = array_intersect_key($fruits_arr, array_flip($ids_arr));
var_dump($result);
https://3v4l.org/jQo6E
Keeping it simple, a loop where you remove items that are not in your keep array.
<?php
$fruits =
[
'foo' => [
'id' => 1,
'fruit' => 'banana'
],
'bar' => [
'id' => 2,
'fruit' => 'orange'
],
'baz' => [
'id' => 3,
'fruit' => 'pear'
],
];
$keep_ids = [1,3];
foreach($fruits as $k=>$v)
if(!in_array($v['id'], $keep_ids))
unset($fruits[$k]);
var_export($fruits);
Output:
array (
'foo' =>
array (
'id' => 1,
'fruit' => 'banana',
),
'baz' =>
array (
'id' => 3,
'fruit' => 'pear',
),
)

Remove the first element (key and value) from an array, turning it into another array

I want to capture the first element of an array and its value in a second array, removing it from the first.
Is there a core PHP function that does what my_function does here?
function my_function(&$array) {
$key = current(array_keys($array));
$value = $array[$key];
unset($array[$key]);
return [$key => $value];
}
$array = [
'color' => 'red',
'car' => 'ford'
'house' => 'cottage',
];
$top = my_function($array);
print_r($top);
print_r($array);
Output:
Array
(
[color] => red
)
Array
(
[car] => ford
[house] => cottage
)
If there's not a core function, is there a simpler way of achieving this behavior? IIRC, passing variables by reference is frowned upon.
Bonus question: is there a word for the combination of both key and element from an array? I feel like 'element' doesn't necessarily include the key.
edit Since there seems to be a commonly held misunderstanding, at least in PHP 7, array_shift does not do the desired behavior. It only returns the first value, not the first element:
$ cat first_element.php
<?php
$array = [
'color' => 'red',
'car' => 'ford',
'house' => 'cottage',
];
$top = array_shift($array);
print_r($top);
print_r($array);
$ php first_element.php
redArray
(
[car] => ford
[house] => cottage
)
Try this (array_splice):
$top = array_splice($array, 0, 1);
The $top will contain the first element and the $array will contain the rest of the elements.
array_splice doesn't always preserve keys, so just get the key and combine with the result of array_shift to also remove it:
$result = [key($array) => array_shift($array)];
If needed, reset the array pointer:
reset($array) && $result = [key($array) => array_shift($array)];
function my_function($array) {
$first_key = key($array);
return array($first_key =>$array[$first_key] );
}
$array = array( 'color' => 'red', 'car' => 'ford','house' => 'cottage' );
$first = my_function($array);
array_shift($array);print_r($first);print_r($array);
I made this function:
function array_extract(array &$array, $num) {
$output = array_slice($array,0, $num);
array_splice($array,0, $num);
return $output;
}
Here's what it does
$ cat test.php
<?php
$test = [234,25,45,78,56];
echo "test:\n";
print_r($test);
while( count($test) ) {
echo "extraction:\n";
print_r(array_extract($test, 2));
echo "\ntest:\n";
print_r($test);
}
$ php test.php
test:
Array
(
[0] => 234
[1] => 25
[2] => 45
[3] => 78
[4] => 56
)
extraction:
Array
(
[0] => 234
[1] => 25
)
test:
Array
(
[0] => 45
[1] => 78
[2] => 56
)
extraction:
Array
(
[0] => 45
[1] => 78
)
test:
Array
(
[0] => 56
)
extraction:
Array
(
[0] => 56
)
test:
Array
(
)
Quite simple:
$array1 = [
'color' => 'red',
'car' => 'ford'
'house' => 'cottage',
];
$array2 = array_unshift($array1);
--> result
$array2 = [
'color' => 'red'
];
$array1 = [
'car' => 'ford'
'house' => 'cottage',
];

Add item to array of arrays based on id

I have an array of arrays set up like so. There are a total of 10 arrays but I will just display the first 2. The second column has a unique id of between 1-10 (each only used once).
Array
(
[0] => Array
(
[0] => User1
[1] => 5
)
[1] => Array
(
[0] => User2
[1] => 3
)
)
I have another array of arrays:
Array
(
[0] => Array
(
[0] => 3
[1] => 10.00
)
[1] => Array
(
[0] => 5
[1] => 47.00
)
)
where the first column is the id and the second column is the value I want to add to the first array.
Each id (1-10) is only used once. How would I go about adding the second column from Array#2 to Array#1 matching the ID#?
There are tons of ways to do this :) This is one of them, optimizing the second array for search and walking the first one:
Live example
<?
$first_array[0][] = 'User1';
$first_array[0][] = 5;
$first_array[1][] = 'User2';
$first_array[1][] = 3;
$secnd_array[0][] = 3;
$secnd_array[0][] = 10.00;
$secnd_array[1][] = 5;
$secnd_array[1][] = 47.00;
// Make the user_id the key of the array
foreach ($secnd_array as $sca) {
$searchable_second_array[ $sca[0] ] = $sca[1];
}
// Modify the original array
array_walk($first_array, function(&$a) use ($searchable_second_array) {
// Here we find the second element of the first array in the modified second array :p
$a[] = $searchable_second_array[ $a[1] ];
});
// print_r($first_array);
Assuming that 0 will always be the key of the array and 1 will always be the value you'd like to add, a simple foreach loop is all you need.
Where $initial is the first array you provided and $add is the second:
<?php
$initial = array(array("User1", 5),
array("User2", 3));
$add = array(
array(0, 10.00),
array(1, 47.00));
foreach ($add as $item) {
if (isset($initial[$item[0]])) {
$initial[$item[0]][] = $item[1];
}
}
printf("<pre>%s</pre>", print_r($arr1[$item[0]], true));
I don't know if I got you right, but I've come up with a solution XD
<?php
$array_1 = array(
0 => array(
0 => 'ID1',
1 => 5
),
1 => array(
0 => 'ID2',
1 => 3
)
);
$array_2 = array(
0 => array(
0 => 3,
1 => 10.00
),
1 => array(
0 => 5,
1 => 47.00
)
);
foreach($array_1 as $key_1 => $arr_1){
foreach($array_2 as $key_2 => $arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key_1][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201648
The short version would look like this:
<?php
$array_1 = array(array('ID1',5),array('ID2',3));
$array_2 = array(array(3,10.00),array(5,47.00));
foreach($array_1 as $key => $arr_1){
foreach($array_2 as$arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201649
Hope that helps :)
A quick and dirty way just to show you one of the more self-explaining ways to do it :)
$users = array(
0 => array(
0 => 'User1',
1 => 123
),
1 => array(
0 => 'User2',
1 => 456
)
);
$items = array(
0 => array(
0 => 123,
1 => 'Stuff 1'
),
1 => array(
0 => 456,
1 => 'Stuff 2'
)
);
foreach($items as $item){
foreach($users as $key => $user){
if($item[0] == $user[1])
array_push($users[$key], $item[1]);
}
}

array's key match with another array php

Ex :
First array:
Array
(
[0] => id
[1] => ADDRESS
[2] => ADDRESS1
[3] => name
)
Second array:
Array
(
[id] => 1
[name] => Ankit
[city] => SURAT
)
Required OUTPUT :
[id] => 1
[ADDRESS]=>
[ADDRESS1]=>
[name] => Ankit
here we can see that value of first array ADDRESS,ADDRESS1 doesn't exist in array 2 key,
so i need value to be set null for ADDRESS,ADDRESS1 and unnecessary field of array 2 is city which key doesn't exist in first array values is need to be unset from result array
CODE :
$field_arr= array('0'=>"id",
"1"=>"ADDRESS",
"2"=>"ADDRESS1",
'3'=>"name",
);
$arr=array("id"=>"1",
'name'=>"Ankit",
"city"=>"Ahmedabad");
$matching_fields =(array_diff_key(array_flip($field_arr),(array_intersect_key($arr,array_flip($field_arr)))));
if(!empty($matching_fields)){
foreach($matching_fields as $key=>$value){
$new_arr[$key]=null;
}
}
print_r($new_arr);
exit;
CURRENT OUTPUT OF NEW ARRAY :
Array
(
[ADDRESS] =>
[ADDRESS1] =>
)
but this is long process.as well as performance also matter. i want whole code reconstruct which i have made and just get output which is required output
Here some more need help need i want same sequence of key of output array same as first array value
my required output :
[id] => 1
[ADDRESS]=>
[ADDRESS1]=>
[name] => Ankit
current output :
[id] => 1
[name] => Ankit
[ADDRESS]=>
[ADDRESS1]=>
Thanks in advance
Just try with:
$keys = array('id', 'name', 'ADDRESS', 'ADDRESS1');
$data = array(
'id' => 1,
'name' => 'Ankit',
'city' => 'SURAT',
);
$output = $data + array_fill_keys($keys, null);
Output:
array (size=5)
'id' => int 1
'name' => string 'Ankit' (length=5)
'city' => string 'SURAT' (length=5)
'ADDRESS' => null
'ADDRESS1' => null
$keys = array_unique(array_merge($field_arr, array_keys($arr)));
$new_array = array();
foreach ($keys as $key)
{
$new_array[$key] = isset($arr[$key]) ? $arr[$key] : '';
}
echo "<pre>";
print_r($new_array);
You can use following;
$first = array(
"id",
"name",
"ADDRESS",
"ADDRESS1"
);
$second = array(
"id" => "1",
"name" => "Ankit",
"city" => "SURAT"
);
foreach ($first as $key) {
if ($second[$key] == null) {
$second[$key] = null;
}
}
var_dump($second);
Here is working demo: Demo

Categories