Jump to content
funstad

Merge duplicate keys in multidimensional array

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

Share this post


Link to post
Share on other sites

What exactly is the error message?  That format you're trying to create is redundant, do you need that specific format for something?

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

If so, I will post the code that produced it.

Roddy

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...