1

I have an objects array as following

 [{"ChannelName":"39-40","Text":"haha"},
  {"ChannelName":"39-40","Text":"lala"}
  {"ChannelName":"40-41","Text":"bla bla"},
  {"ChannelName":"40-41","Text":"kha kha"}]

How can I check duplicate value in ChannelName. What I need to do is when ChannelName exists in array object, I want to replace the ChannelName with new Text. How php check duplicate ChannelName and how to replace of old Text attribute with new Text attribute if ChannelName duplicate?

1

1 Answer 1

1

Try this solution.

$json = <<<JSON
[{"ChannelName":"39-40","Text":"haha"},
{"ChannelName":"39-40","Text":"lala"},
{"ChannelName":"40-41","Text":"bla bla"},
{"ChannelName":"40-41","Text":"kha kha"}]
JSON;

$json_array = json_decode( $json, TRUE );

$new_array = array();
$exists_array    = array();
foreach( $json_array as $element ) {
    if( !in_array( $element['ChannelName'], $exists_array )) {
        $exists_array[]    = $element['ChannelName'];
    }
    else{
        $element['ChannelName'] = 'New Value';
    }
    $new_array[] = $element;
}

print json_encode( $new_array );

Here at New Value section you can change your value as per your requirement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.