0

i got response (json) from web service and converted / decoded it into php array.

converted array php:

$data = [
    [
        'id' => '01',
         'name' => 'ABC',
         'label' => 'color',
         'value' => '#000000'
    ],[ 
         'id' => '01',
         'name' => 'ABC',
         'label' => 'active',
         'value' => true
    ],[
         'id' => '02',
         'name' => 'DEF',
         'label' => 'color',
         'value' => '#ffffff'
    ],[
         'id' => '02',
         'name' => 'DEF',
         'label' => 'active',
         'value' => false
    ]
];

expected array output:

$data = [
    [
         'id' => '01',
         'name' => 'ABC',
         'color' => '#000000',
         'active' => true,
    ],[ 
         'id' => '02',
         'name' => 'DEF',
         'color' => '#ffffff',
         'value' => false
    ]
];

What php function is suitable for that case? thanks in advance

2
  • 2
    usually a foreach is involved, did you try it out? Commented Sep 4, 2019 at 2:40
  • have you tried anything? Commented Sep 4, 2019 at 5:13

3 Answers 3

1

You can simple use foreach

$r = [];
foreach($data as $v){
  if(isset($r[$v['id']])){
    $r[$v['id']][$v['label']] = $v['value'];
  }else{
    $r[$v['id']] = [
        'id'        => $v['id'],
        'name'      => $v['name'],
        $v['label'] => $v['value']
    ];
  } 
}

Live example : https://3v4l.org/ilkGG

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

Comments

0
$data = json_decode($data); //decode the json into a php array

foreach ($data as $key=>$subArray){ //loop over the array

  //check and see if value is either true/false
  if (is_bool($subArray['value'])){ 
   $processedArray[] = $subArray; //build output
  }

}

print_r($processedArray); //output/dump array for debugging

Comments

0

In this case, you have to loop through the array and remove duplicates, Try the given way

$data = json_decode($data , true);
$filtered = array();
for($i = 0 ; $i < count($data) ; $i++){
    if(!array_key_exist($data[$i]['id'] , $filtered )){
        $filtered [$data[$i]['id']] = $data[$i];
        continue;
    }  
}

$filtered = array_values($filtered);

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.