Merging One Array's Key on Second Array's Values

I have two two-dimensional arrays that need to be merged into a single multi-dimensional array that has all values based on matching the key in one to one of the values in the other. The example below has been simplified as the first array typically has many more entries so I showed only the first and the number of key/value pairs in the first array may be greater or fewer and even in a different order. I see another similar question asked here but it relates to known keys and values but on mine they are not known from usage to usage so it must be able to find the match itself.

No clue where to start so I hope someone here can help!

// First array to match PhotoName key . . .

Array
(
    [0] => Array
        (
            [ID] => 42
            [PhotoCaption] => Some caption for Image1
            [PhotoName] => Image1.jpg
            [AlbumName] => Name Of This Album
        )
)

// . . . to FieldName value

Array
(
    [0] => Array
        (
            [FieldType] => 5
            [FieldTitle] => Caption
            [FieldName] => PhotoCaption
            [LookupQuery] => 
        )

    [1] => Array
        (
            [FieldType] => 1
            [FieldTitle] => Photo Name
            [FieldName] => PhotoName
            [LookupQuery] => 
        )

    [2] => Array
        (
            [FieldType] => 1
            [FieldTitle] => Album Name
            [FieldName] => AlbumName
            [LookupQuery] => 
        )
	[3] => Array
        (
            [FieldType] => 0
            [FieldTitle] => 
            [FieldName] => ID
            [LookupQuery] => 
        )
)

// Rough sample of merged array that it should build (illustration only, syntax probably not correct)

Array
(
    [0] => Array
        (
            [ID] => 42
				[0] => Array
					(
						[FieldType] => 0
						[FieldTitle] => 
						[FieldName] => ID
						[LookupQuery] => 
					)
	
            [PhotoCaption] => Some caption for Image1
				[1] => Array
					(
						[FieldType] => 5
						[FieldTitle] => Caption
						[FieldName] => PhotoCaption
						[LookupQuery] => 
					)
			
            [PhotoName] => Image1.jpg
				[2] => Array
					(
						[FieldType] => 1
						[FieldTitle] => Photo Name
						[FieldName] => PhotoName
						[LookupQuery] => 
					)
			
            [AlbumName] => Name Of This Album
				 [3] => Array
					(
						[FieldType] => 1
						[FieldTitle] => Album Name
						[FieldName] => AlbumName
						[LookupQuery] => 
					)
        )
)

The 2nd array needs to be indexed by the FieldName, so that you don’t need to search to find the matching entry, e.g. -

Array
(
    [PhotoCaption] => Array
        (
            [FieldType] => 5
            [FieldTitle] => Caption
            [FieldName] => PhotoCaption
            [LookupQuery] => 
        )
    [PhotoName] => Array
        (
            [FieldType] => 1
            [FieldTitle] => Photo Name
            [FieldName] => PhotoName
            [LookupQuery] => 
        )
    [AlbumName] => Array
        (
            [FieldType] => 1
            [FieldTitle] => Album Name
            [FieldName] => AlbumName
            [LookupQuery] => 
        )
    [ID] => Array
        (
            [FieldType] => 0
            [FieldTitle] => 
            [FieldName] => ID
            [LookupQuery] => 
        )
)

Assuming the first array is named $i, and the 2nd array is named $f (indexed by the FieldName), the following produces the result you have shown -

$result = [];
foreach($i as $key1=>$data)
{
	foreach($data as $key2=>$value)
	{
		$result[$key1][$key2] = $value;
		$result[$key1][] = $f[$key2];
	}
}

echo '<pre>'; print_r($result); echo '</pre>';

Thank you! That works perfectly! I never thought of indexing the array so I was trying to make it more difficult than it is.

A quick addendum question. How can I put the two together into a more manageable 2-dimensional array something like this?

Array
(
    [0] => Array
       (
        [PhotoCaption] => 
        [FieldType] => 5
        [FieldTitle] => Caption
        [FieldName] => PhotoCaption
        [LookupQuery] => 
        )
)

What’s the overall goal? What you have been showing is what you are trying to make ‘work’. What the overall goal is, i.e. what you are using the data for, determines what the result should be.

I suspect the 1st array are data values, the 2nd array are form field types, and you are dynamically producing a from. If so, the elements in 1st array need to just become ‘value’ elements in the corresponding field in the resultant array, something like -

$result = [];
foreach($i as $key1=>$data)
{
	foreach($data as $key2=>$value)
	{
		$result[$key1][$key2] = $f[$key2];
		$result[$key1][$key2]['value'] = $value;
	}
}

echo '<pre>'; print_r($result); echo '</pre>';

This programming is a supplement to some I already have that makes forms from database entries using a series of functions to provide the specific form fields from FieldType to provide the actual HTML for each field. In this case, it’s for editing multiple entries at once.

Seems to be working well and pulling up the needed values but I am not sure how to access them by name! I expected to be able to use variable variables as ${'_'.$key} = $value; but in a 3-layer foreach, they do not appear to work as expected so what do I need to make use of the values? echo "$key = $value<br>\n"; seems to give them all so not sure what’s needed.

For example, using echo $_FieldValue; gives Undefined variable $_FieldValue but then goes on and shows all the $_FieldValue values although it shows each five times.

Here is the full function:

// EXPIREMENTAL BASIC EDITABLE GRID
function EditableGrid($conn, $_FormID=0) {
	// SELECT GRID OPTIONS FROM formsgrid TABLE
	$sqlGrid =	"SELECT  
							`ID`, 
							`UseID`, 
							`FormID`, 
							`GridTable`, 
							`GridQuery`, 
							`FileFolder`,
							`Fields`
							FROM `formsgrid` 
							WHERE `FormID` = ?";
	$rowGrid = DBRun($conn, $sqlGrid, "Select", $_FormID, "assoc");

	$_EnableMulti = TRUE;

	if ($_EnableMulti == TRUE && is_array($rowGrid) && isset($_POST['SearchID'])) :
			$gridID = $_POST['SearchID'];

		// CREATE VARIABLES OF EACH DATABASE-BASED FORM VALUE
		foreach ($rowGrid as $row => $val) :
			if (is_string($row)) :
				$$row = $val;
			endif;
		endforeach;

		// RETRIEVE TABLE VALUES FOR GRID RECORDS
		$rowValues = DBRun($conn, $GridQuery, "Multiple", $gridID, "assoc");

		// VALUE PAIRS FROM $Fields COLUMN
		$FieldVals = createPairsMulti($Fields, 4);
		
		// INDEX THE $FieldVals ARRAY ON FieldName
		$FieldValsIndexed = array_column($FieldVals, null, 'FieldName');

		// BUILD ARRAY CONTAINING VALUES AND FORM PARAMETERS TOGETHER
		$resultmerged = [];
		foreach($rowValues as $key1=>$data) :
			foreach($data as $key2=>$value) :
				$resultmerged[$key1][$key2] = $FieldValsIndexed[$key2];
				$resultmerged[$key1][$key2]['FieldValue'] = $value;
			endforeach;
		endforeach;

		foreach ($resultmerged as $val) :
			foreach($val as $field) :
				foreach ($field as $key => $value) :
					if (is_string($key)) :
						${'_'.$key} = $value;
						echo "$key = $value<br>\n";
					endif;
				endforeach;
			endforeach;
		endforeach;
	endif;
}

Don’t use variable variables, ever. Just use the original variable that data is in. You are trying to dynamically produce (and later process) a form. You don’t want discrete variables that you must then write out bespoke code, or use more variable variables, to access. Arrays are for sets of data where you will operate on each member in the set in the same or similar way. Keep all this data as an array. The point in the posted code where you are creating the $_… variable variable//echoing the “$key = $value”… is where you should be using this data to produce the desired output.

Yes but I cannot get any values there whether by variable variables or otherwise which was the point of the question as I’m not sure how to do it. The form is not being created dynamically as such but rather through a function so what I actually need is to build an array containing specific values needed for each field to call and pass into the function but that is where I am having difficulty. As I can’t seem to call the values, I can’t build the array.

You already have an array of the data for each field, in $field -

Array
(
    [FieldType] => 0
    [FieldTitle] => 
    [FieldName] => ID
    [LookupQuery] => 
    [FieldValue] => 42
)
Array
(
    [FieldType] => 5
    [FieldTitle] => Caption
    [FieldName] => PhotoCaption
    [LookupQuery] => 
    [FieldValue] => Some caption for Image1
)

I need to pass these yet to be created arrays one group at a time into the fieldType() function to generate each field so are you saying that I need one more foreach to fetch out each group? I can’t just send it any function as it needs these values and a few other static ones that the EditableGrid() function provides outside the loops. As I don’t usually call the fieldType() function directly this way, I’m not actually sure yet what it needs but I do need to specify the values to use.

I only see the information you supply in the posts.

What I am asking is how to create variables from this data so that I can actually use it. Otherwise it would take thousands of lines of code to post everything.

The data is already in a variable. You don’t need to waste your time copying variables to other variables.

Without an example of what you are trying to accomplish, no one can help. What’s the code for the fieldType() function?

Surely you’re not serious. There are nearly 1000 lines of code in that function alone along with calls to a number of other functions each with a similar number of lines. I don’t see how knowing all that code is an answer to how to create variables from the function that is in question here. There are values from a 3-dimensional array and I simply need to know how to use them.

You are stuck thinking you must have a discrete variable to supply as an input to a function, and the only way you know to do that is to repeat some code you saw that loops over all the elements in an array. You can use anything that results in a value. A literal value, a variable, an element of an array, the result of a function call, a math expression, a logic expression, … WHAT is the input parameter definition for the fieldType() function?

Here, just as a guess -

fieldType($field['FieldType']);

I’m not stuck thinking anything but I know I now have to assemble an array of values to pass into the function and they must have specific names. At the moment, it’s still up in the air as I said because I don’t typically call the function directly. Rather, it is called from within another much longer function and the array being fed into it is far more than is actually needed. That said, the most basic values are the field name, title, field type and any lookup query it might need and there may be a few more things that I’ve not added yet until I know what they are.

On your thought of $field['FieldType']; as an example, it does give a value but it gives each five times which is why I asked if it needs another foreach loop. It already has three so is getting a bit out of control!

Your description is pointless. Without knowing what the input parameter(s) are, there’s no way to help you. If the existing $field array is incorrect, the correct way of fixing this is to change the code leading up to that point, so that it does have the correct information in it.

Sponsor our Newsletter | Privacy Policy | Terms of Service