Jump to content

Merge duplicate keys in multidimensional array


funstad
 Share

Recommended Posts

Hello,

I have this array print:

Array (
	[0] => Array (
		[name] => color
		[value] => red
	)
	[1] => Array (
		[name] => color
		[value] => blue
	)
	[2] => Array (
		[name] => color
		[value] => green
	)
	[3] => Array (
		[name] => age
		[value] => 16
	)
) 

I want to receive this result:

Array (
	[color] => Array (
    	[name] => color
    	[value] => red, blue, green
	)
	[age] => Array (
    	[name] => age
		[value] => 16
	)
) 

it works using the following php code:

foreach ($feature_names as $row) {
	if (!isset($result[$row["name"]])) {
		$result[$row["name"]]["name"] = $row["name"];
		$result[$row["name"]]["value"] = $row["value"];
	} else {
		$result[$row["name"]]["value"] .= ", " . $row["value"];
	}
}

 

How ever in PHP 7.1  using the code $result[$row["name"]]["name"] = $row["name"]; generates an error.

Does someone know a work around?

Thanks in advance!

Edited by funstad
Link to comment
Share on other sites

Will the following result satisfy you?

Array (
	[color] => Array (
		[name] => color
		[value] => Array (
			[0] => red
			[1] => blue
			[2] => green
		)
	)
	[age] => Array (
		[name] => age
		[value] => 16
	)
)

Roddy

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...