1

I have a array as in the example. With the code I wrote, I get an output like in Output1.

Question: I am requesting a service different from my own application. The answer is an array and it contains id information. There is permission () for authorization control. The permission function returns user privileges as true and false. But I couldn't write the correct syntax because I couldn't remember this function completely. When I use my own code, I can pull the users who have permission as in output1. But I want the pagination information to remain in the array. As in Output2. What method should I apply?

This array is an example. I just tried to explain my own problem.

My code=>(Laravel 5.8)

$response = ….get(url)………

$list = $response->getBody()[‘content’];

$collection = collect($list);

$filtered = $collection->filter(function ($item) [
    return auth()->user->permission($item['id'])
]);

Return [‘content’ => $filtered];


Raw Response:

[
  "paginate"=> 
  [
      "page"=> 5,
      "per_page"=> 20,
      "page_count"=> 20,
      "total_count"=> 521,
      "Links"=> [
        ["self"=> "/products?page=5&per_page=20"],
        ["first"=> "/products?page=0&per_page=20"],
      ]
  ],
  "content"=> [
    [
      "id"=> 1,
      "name"=> "Widget #1",
    ],
    [
      "id"=> 2,
      "name"=> "Widget #2",
    ],
    [
      "id"=> 3,
      "name"=> "Widget #3",
    ]
  ]
]

Output1:

[
  "content"=> 
  [
      "id"=> 1,
      "name"=> "Widget #1",
    ],
   ----------------------> Authorized users(id= 1, 3) here, but no pagination.
[
      "id"=> 3,
      "name"=> "Widget #3",
    ]
  ]


expected output:

[
  "paginate"=> 
  [
      "page"=> 5,
      "per_page"=> 20,
      "page_count"=> 20,
      "total_count"=> 521,
      "Links"=> [
        ["self"=> "/products?page=5&per_page=20"],
        ["first"=> "/products?page=0&per_page=20"],
      ]
  ],
  "content"=> [
    [
      "id"=> 1,
      "name"=> "Widget #1",
      "uri"=> "/products/1"
    ],
    [
      "id"=> 3,
      "name"=> "Widget #3",
      "uri"=> "/products/3"
    ]
  ]
]
14
  • 2
    Maybe I'm missing something, but the "example" and "Output2" look the same to me (minus the record with id 2 in the latter) Commented Feb 11, 2020 at 18:12
  • @patrickQ yes you are right, i just want to delete id 2 without breaking the basic json structure. I'm losing all paginate information in Output1. After deleting id 2, I want a json to remain in output2 Commented Feb 11, 2020 at 18:18
  • Please include the actual code that you used in the body of the question. Commented Feb 11, 2020 at 18:21
  • 1
    Also, your example JSON isn't actually valid JSON. Please provide us with something that is useable and a true representation of the JSON used by your code. Commented Feb 11, 2020 at 18:24
  • @PatrickQ I can't share real Json data, Because I don't have access right now. I added the code I used with Laravel. User permissions return me with the permission () function as true and false. I want to delete the unauthorized ones. Commented Feb 11, 2020 at 18:42

2 Answers 2

2

So, if what are you saying is correct it looks like you are already properly filtering your content to exclude those with the unwanted ids. Good job! Now, you want the JSON back that also contains your pagination data. First let's step through your code to see how we ended up here:

$response = ….get(url)………

$list = $response->getBody()[‘content’];

Right here, in the first two lines, we see that you have selected ONLY the content from your response body and stored it in $list.

$collection = collect($list);

$filtered = $collection->filter(function ($item) [
    return auth()->user->permission($item['id'])
]);

Now, you're taking that content and filtering it based on id.

Return [‘content’ => $filtered];

And, lastly, you are returning the filtered content. So, nothing has been deleted at all - you've just pulled out the content, filtered it, and returned it. Your pagination data is still sitting right where you left it. In order to get the JSON you want to return you could adjust the way you are pulling out content and filtering it, but since I don't know many details of what you're doing or why and your filter is already working my instinct is why bother? You could just take your pagination data and combine it with your filtered content and then you would have exactly what you're looking for:

$response = ….get(url)………

$list = $response->getBody()[‘content’];
$pagination = $response->getBody()[‘pagination’];

$collection = collect($list);

$filtered = $collection->filter(function ($item) [
    return auth()->user->permission($item['id'])
]);

$alldata = // combine your pagination and filtered objects 

Return [‘data’ => $alldata];

Note that I did not show how to combine pagination and the filtered content - this is because I'm not sure what type of objects you've got at this point. Since your sample output is not really proper JSON I'm not sure if pagination really is supposed to be a list/array or if it's just the way you've written your examples, I'm not sure if these are strings or if they've been parsed, etc. So strings would require appending one to the other, collections would use combine(), and so on.

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

Comments

1

Your array is an invalid array ! So I couldnt try it, as I mentioned in comment!

What I understand from reading all your edits, Here some examples how you can remove id 2 from array in php:

Before starting : we have an option to ignore id 2 in php where clause like so

SELECT * FROM table WHERE id NOT IN (2)

OR 

SELECT FROM table WHERE id <> 2 

You can ignore id 2 when querying then you will have an array without id 2, lets contine with arrays

if you want to remove a specific value in array do the following.

Remove from an Associative Array

   $YourArray = array("id"=>"2","name"=>"somename");

    //use array key exist to find if id exist

    $test = array_key_exists("id",$YourArray);
      if($test == 2){
        unset($YourArray['id']); //Here you unset id 2
      }
    print_r($YourArray); //result of new array

Second solution with multdimential arrays:

// PHP program to creating two  
// dimensional associative array 
$data = array( 

    // Ankit will act as key 
    "paginate" => array( 

        // Subject and marks are 
        // the key value pair 
        "id" => 1, 
        "name" => "Widget #1",  
        "uri"=> "/products/1"
    ), 

    // Ram will act as key 
    "content" => array( 

        // Subject and marks are 
        // the key value pair 
        "id" => 2, 
        "name" => "Widget #1",  
        "uri"=> "/products/1"
    ),  
); 

echo "Display Marks: \n"; 


foreach ($data as $key => $subArr) {
    if($subArr['id'] == 2){
    unset($subArr['id']);
    $data[$key] = $subArr; 
    }
}
print_r($data); 

Here is the demo : https://3v4l.org/mvZPN

If you want to remove id and all its elements in array : array_filter(); used

$test = array_filter($data, function($data) { return $data['id'] != 2; });

print_r($test);

Here is the demo : https://3v4l.org/UgNqu

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.