0

I'm trying to unset some elements of JSON Array, so if pname value start with XX it should unset. Normal JSON String gives me this

$json = str_replace('"', '"', $loc);

[{"uid":"352","pcode1":"AB1","pname":"XXAB1"},....}]

If I hardcode pname value like this

foreach ($json as $key => $value) 
     {
        if (in_array('XXAB1', $value)) {
                unset($json[$key]);
            }
    }
    $j = json_encode($json);
    echo $j;

it works unsets that array but how can I do this dynamically ? So that each pname value begins with XX can be unsets.

2 Answers 2

2

You can use preg_match like as

if(preg_match('/^[X]{2}/',$value['pname'])){
    unset($json[$key]);
}

Demo

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

2 Comments

Thanks for your reply, I've tried your suggestion instead of in_array() but not having much luck.
If I don't use json_decode($json,true); it works, very strange. final code that worked $json = str_replace('"', '"', $loc); foreach ($json as $key => $value) { if(preg_match('/^[X]{2}/',$value['pname'])){ unset($json[$key]); } } $j = json_encode($json); echo $j; Thank you very much
1

Within your foreach, you could use strpos to determine whether XX resides at the beginning of the string.

Using === strictly checks that 0 is returned and not false

<?php

$json = json_decode('[{"uid":"352","pcode1":"AB1","pname":"XXAB1"},{"uid":"352","pcode1":"AB1","pname":"XAB1"}]',true);

foreach ($json as $key => $value) {
    if(strpos($value['pname'], 'XX') === 0) {
        unset($json[$key]);
    }
}

$j = json_encode($json);
echo $j;

print_r($json);

https://3v4l.org/hZLDP

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.