merge two associative arrays add titles - php

I have two arrays
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
I wish to merge them on the ID column and have my final array be in this form
$employees = array(
array(
'name' => 'Jason',
'occupation' => 'Chef'
),
array(
'name' => 'Mike',
'occupation' => 'Mechanic'
),
...
);
I know I can array combine them like below:
$new_array = array_combine(array_values($Array_1), array_values($Array_2));
but how would I add the titles "Name": and "Occupation":

Can you try this,
$Employees = array();
foreach($Array_1 as $key=>$value):
$Employees['Employees'][] = array('Name'=>$value, 'Occupation'=>$Array_2[$key]);
endforeach;
echo "<pre>";
print_r($Employees);
echo "</pre>";
echo json_encode($Employees);
OP:
{"Employees":[{"Name":"Jason","Occupation":"Chef"}, {"Name":"Mike","Occupation":"Mechanic"}]}

i dont know how the array look. but you can try my two solution
First solution
$array1 = array("id" => array("id1", "id2", "id3"), "names" => array("name1", "name2", "name3"));
$array2 = array("id" => array("id1", "id2", "id3"), "occupation" => array("occupation1", "occupation2", "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1["id"] as $index => $key) {
$employee = array();
$occupation = in_array($key, $array2["id"]) ? $array2["occupation"][$index] : false;
if ($occupation === false) {
continue;
}
$employee["name"] = $key;
$employee["occupation"] = $occupation;
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
Second Solution
$array1 = array("id1" => array("names" => "name1"), "id2" => array("names" => "name2"), "id3" => array("names" => "name3"));
$array2 = array("id1" => array("occupation" => "occupation1"), "id2" => array("occupation" => "occupation2"), "id3" => array("occupation" => "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1 as $key => $value) {
$employee = array();
if (!isset($array2[$key])) {
continue;
}
$employee["name"] = $value["names"];
$employee["occupation"] = $array2[$key]["occupation"];
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
i hope my code can help.

you can try this
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
$filter_array = array("employees" => array());
foreach($Array_1 as $key => $value){
$employee = array();
if(!isset($Array_2[$key])){ continue; }
$employee["name"] = $value;
$employee["occupation"] = $Array_2[$key];
array_push($filter_array["employees"], $employee);
}

EDIT 2
Aah, now I see the phpfiddle in the comments and the edit to the OP. So, the ID is already the key of the array? ... Then just do
foreach($Array_1 as $key_1 => $value_1) {
$new_Array[$key_1]['Names'] = $Array_1['Names'];
}
foreach($Array_2 as $key_2 => $value_2) {
$new_Array[$key_2]['Occupation'] = $Array_2['Occupation'];
}

use array_walk . It runs a function per each array item .combine them in the function .

Related

How to merge array using UUID value

I have the following code :
<?php
$arr1 = array();
$arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
$arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
$arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];
$arr2 = array();
$arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
$arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
$arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];
$new_arr1 = array();
foreach ($arr1 as $key => $value) {
if(isset($new_arr1[$value['UUID']])){
$new_arr1[$value['UUID']] += ['name_a' => $value['name']];
}else{
$new_arr1[$value['UUID']] = ['name_a' => $value['name']];
}
}
$new_arr2 = array();
foreach ($arr2 as $key => $value) {
if(isset($new_arr2[$value['UUID']])){
$new_arr2[$value['UUID']] += ['name_1' => $value['name']];
}else{
$new_arr2[$value['UUID']] = ['name_2' => $value['name']];
}
}
$final_array = array_combine($new_arr1, $new_arr2);
var_dump($final_array);
Which give me the following error :
Warning: Array to string conversion in /home/user/scripts/code.php on line 32
Snippet :
https://sandbox.onlinephpfunctions.com/c/cf5fd
I want to use the UUID as an array id.
here is the expected output :
Array
(
[123a-123a] => Array
(
[name_1] => A1
[name_2] => A2
)
[123b-123b] => Array
(
[name_1] => B1
[name_2] => B2
)
[123c-123c] => Array
(
[name_1] => C1
[name_2] => C2
)
)
Instead of use array_combine you need to use array_merge_recursive because is multidimensional
Snippet:
https://sandbox.onlinephpfunctions.com/c/eae35
Reference:
array_merge_recursive
No array_combine nor intermediate arrays needed, just construct new array from those you already have:
$arr1 = array();
$arr1[] = ['UUID' => '123a-123a', 'name' => 'A1'];
$arr1[] = ['UUID' => '123b-123b', 'name' => 'B1'];
$arr1[] = ['UUID' => '123c-123c', 'name' => 'C1'];
$arr2 = array();
$arr2[] = ['UUID' => '123a-123a', 'name' => 'A2'];
$arr2[] = ['UUID' => '123b-123b', 'name' => 'B2'];
$arr2[] = ['UUID' => '123c-123c', 'name' => 'C2'];
$final_array = [];
foreach( array_merge($arr1, $arr2) as $entry ){
if( empty( $final_array[$entry['UUID']] ) )
$final_array[$entry['UUID']] = ['name_1' => $entry['name']];
else
$final_array[$entry['UUID']][ 'name_' . (count( $final_array[$entry['UUID']] ) + 1) ] = $entry['name'];
}
print_r($final_array);
array_combine creates an array by using one array for keys and another for its values. In your case, each of the 2 arrays have individual subarrays in them. Hence the error when it tries to make one of the subarrays as a string(which it can't).
In your code, you can use a single $new_arr and the make the code more concise with the null coalescing operator(??) like below:
<?php
$new_arr = array();
foreach (array_merge($arr1,$arr2) as $key => $value) {
$new_arr[$value['UUID']] = $new_arr[$value['UUID']] ?? [];
$new_arr[$value['UUID']] += [('name_' . (count($new_arr[$value['UUID']]) + 1)) => $value['name']];
}
print_r($new_arr);
Online Demo

PHP foreach with a condition only extract first value

I have an array as
$apps = array(
array(
'id' => '2',
'name' => 'Popcorn'
),
array(
'id' => '1',
'name' => 'EveryCord'
),
array(
'id' => '2',
'name' => 'AirShou'
),
Here I want to print names where id="2". So I tried it with following code.
foreach ( $apps as $var ) if ($var['id'] == "2") {
echo $var['name']
}
The problem is that it only print first result of the array as
"Popcorn".
But I want to extract all result which are
"Popcorn and Airshou"
How can I fix this. Can someone help me !
Try this;
$apps = [
['name' => 'Fish', 'id' => 2],
['name' => 'Chips', 'id' => 1],
['name' => 'Sticks', 'id' => 2],
];
$using = [];
foreach ( $apps as $var ) {
if ($var['id'] == "2") {
$using[] = $var['name'];
}
}
echo implode(" and ", $using);
RESULT:
You can create a sample array.
And append the name to it, if it is id=2
Code:
$apps = [
['id' => '2', 'name' => 'Popcorn'],
['id' => '1', 'name' => 'EveryCord'],
['id' => '2', 'name' => 'AirShou']
];
$names = [];
if (! empty($apps)) {
foreach ($apps as $elem) {
if ($elem['id'] == 2) {
$names[] = $elem['name'];
}
}
}
$finalName = ! empty($names) ? implode(' and ', $names) : '';
echo '<pre>';print_r($finalName);echo '</pre>';
// Output: Popcorn and AirShou
You can filter the array on the item id and then retrieve the column name:
array_column(array_filter($apps, function($v){return '2' === $v['id'];}), 'name')
result:
array(2) {
[0] =>
string(7) "Popcorn"
[1] =>
string(7) "AirShou"
}
Change your loop by this code, and you will got both names,
foreach ( $apps as $var ){
if ($var['id'] == "2") {
echo $var['name'];
}
}
Just grab names in array then implode it like this:
$temp = array();
foreach ( $apps as $var ) if ($var['id'] == "2") {
$temp[] = $var['name']
}
echo implode(' and ', $temp);

PHP Convert single dimensional array to nested array

How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?
Example:
Input:
$input = array('Orange','Apple','Banana');
Expected Output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
This is my code:
$categories = array('Orange','Apple','Banana');
$count = count($categories);
for($i=0;$i<=$count;$i++){
if(isset($categories[$i+1])){
$parent = $categories[$i+1]; // parent
$categories[$i+1]=array(
'name' => $categories[$i+1],
'sub_category' => array('name' => $categories[$i])
);
}
}
$categories = $categories[$count-1];
var_dump($categories);
My code is sloppy and I also get the following incorrect output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
);
Edit 1:
The problem/solution provided here does not seem to be answering my question.
You could use simple recursion technique:
function toNestedArray(array $input, array $result = [])
{
$result = ['name' => array_pop($input)];
if (count($input)) {
$result['sub_category'] = toNestedArray($input, $result);
}
return $result;
}
$categories = array('Orange','Apple','Banana');
$count = count($categories);
$categories2=array();
for($i=$count-1;$i>0;$i--){
if($i-2>-1){
$categories2=array(
'name'=>$categories[$i],
'sub_category'=>array('name'=>$categories[$i-1],'sub_categories'=>array('name'=>$categories[$i-2]))
);
}
}
echo "<pre>";
print_r($categories2);
echo "</pre>";
A simple option is to loop over the $input array, building the $output array from inside to out.
$output = array();
foreach ($input as $name) {
if (empty($output)) {
$output = array("name" => $name);
} else {
$output = array("name" => $name, "sub_category" => $output);
}
}

PHP how to get value from multidimensional array?

I have an array in a class and want to obtain the 'Apple' key value ('iPhone').
I assume a for each loop needs to be used.
How would I go about doing this?
UPDATE: I also need to specify the customerType and productType key values.
class Products {
public function products_list() {
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr = array();
$productsArr[] = array(
'customerType' => 'national',
'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
}
}
I have created a function that you can more or less give it any product and it will return the key and value from the array
<?php
class Products
{
public function products_list()
{
$customerType = 'national';
$productType = 'phones';
$phoneType = 'Apple';
$productsArr[] = array(
'customerType' => 'national', 'productType' => array(
'phones' => array(
'Apple' => 'iPhone',
'Sony' => 'Xperia',
'Samsung' => 'Galaxy'
),
'cases' => array(
'leather' => 'black',
'plastic' => 'red',
),
),
'international' => array(
'phones' => array(
'BlackBerry' => 'One',
'Google' => 'Pixel',
'Samsung' => 'Note'
),
'cases' => array(
'leather' => 'blue',
'plastic' => 'green'
),
)
);
echo $this->get_value($phoneType, $productsArr) .'<br>';
echo $this->get_value($customerType, $productsArr) .'<br>';
echo $this->get_value($productType, $productsArr) .'<br>';
}
function get_value($product, array $products)
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($products), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($iterator as $key => $value) {
if (is_string($value) && ($key == $product)) {
return 'key ->' . $key .' value ->'.$value;
}
}
return "";
}
}
$phone_products = new Products();
$phone_products->products_list();
To use it within the class just call
$this->get_value($phoneType, $productsArr);
from without the class call
$phone_products = new Products();
echo ($phone_products->get_value($phoneType, $productsArr));
//output: key ->Apple value ->iPhone
NB: $phoneType, $productsArr will either be defined the methods they are being used in or passed from other methods or define global variables within the class.
If you want single entry:
echo $productsArr[0]['productType']['phones']['Apple']."<br />";
If there are multiple data, you can use foreach:
foreach ($productsArr as $prod){
echo $prod['productType']['phones']['Apple']."<br />";
}
just try
foreach($productsArr[0]['productType']['phones'] as $phones){
echo $phones[$phoneType]; }
foreach($productsArr as $key1 => $data1 ){
if(is_array($data1))
foreach($data1 as $key2 => $data2 ){
if(is_array($data2))
foreach($data2 as $key3 => $data3 ){
if(array_key_exists('Apple', $data3)) {
echo $data3['Apple'] ."\n";
}
}
}
}

Convert array keys to a string in PHP

Example Array:
$array = array([key1] =>
array([key11] =>
array([key111] => 'value111',
[key112] => 'value112',
[key113] => 'value113',
[key114] => array(A,B,C,D),
),
),
);
I need an output as below array:
array([key1/key11/key111] => 'value111',
[key1/key11/key112] => 'value112',
[key1/key11/key113] => 'value113',
[key1/key11/key114] => 'A,B,C,D' );
and i have tried using this function,
function listArrayRecursive($someArray, &$outputArray, $separator = "/") {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($someArray), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $k => $v) {
if (!$iterator->hasChildren()) {
for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
$p[] = $iterator->getSubIterator($i)->key();
}
$path = implode($separator, $p);
$outputArray[] = $path;
}
}
}
$outputArray = array();
listArrayRecursive($array, $outputArray);
I cant able to find how to achieve this by using the above function for "key1/key11/key114" getting value as i expected. Please help me on this.
Input:
$array = array(
'key1' => array(
'key11' => array(
'key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array('A','B','C','D'),
),
'key12' => array(
'key121' => 'value121',
'key122' => 'value122',
'key123' => 'value123',
'key124' => array('A','B','C','D'),
),
),
'key2' => array(
'key21' => array(
'key211' => 'value111',
'key212' => 'value112',
'key213' => 'value113',
'key214' => array('A','B','C','D'),
),
),
);
Script:
function remap_keys($input, $max_depth, $separator = '/', /* reserved */ $keychain = array(), /* reserved */ &$output = array())
{
foreach ($input as $key => $element)
{
$element_keychain = array_merge($keychain, (array)$key);
if (($max_depth > 1) && is_array($element))
remap_keys($element, $max_depth -1, $separator, $element_keychain, $output);
else
$output[implode($separator, $element_keychain)] = implode(',', (array)$element);
}
return $output;
}
$array = remap_keys($array, 3);
print_r($array);
Output:
Array
(
[key1/key11/key111] => value111
[key1/key11/key112] => value112
[key1/key11/key113] => value113
[key1/key11/key114] => A,B,C,D
[key1/key12/key121] => value121
[key1/key12/key122] => value122
[key1/key12/key123] => value123
[key1/key12/key124] => A,B,C,D
[key2/key21/key211] => value111
[key2/key21/key212] => value112
[key2/key21/key213] => value113
[key2/key21/key214] => A,B,C,D
)
http://ideone.com/pqH45h
$array = array('key1' =>
array('key11' =>
array('key111' => 'value111',
'key112' => 'value112',
'key113' => 'value113',
'key114' => array(A,B,C,D),
),
),
);
function implode_arr_keys($array, $output_arr = array(), $cur_key = FALSE) {
foreach($array as $key => $value) {
if(is_array($value)) {
return implode_arr_keys($value, $output_arr, ($cur_key == FALSE ? $key : $cur_key.'/'.$key));
} else {
if(!is_numeric($key))
$output_arr[$cur_key.'/'.$key] = $value;
else
$output_arr[$cur_key] = $array;
}
}
return $output_arr;
}
print_r($array);
print_r(implode_arr_keys($array));

Categories