I have a very complicate condition, and I just can't come up with a logic that works perfect. Here is what I need to do: I fetch 10 article through an API, and I need to display them in right post order. Problem is sometimes articles changes its order automatically. What I need to do is no matter if they change their order or not their order on my page stays static. for example if array('itemA', 'itemB', 'itemC', 'itemD') becomes array('itemC', 'itemA', 'itemB', 'itemD')
I still wanna show in original order, which would be itemA, B, C and D.
I tried in_array() function to check if article is already there, but it does not seems to be working right.
Take a look:
$post_array = array();
foreach ($Info AS $key => $post_array){
if (!in_array($Info[$key]->postId, $post_array)){
array_unshift($post_array, $Info[$key]);
echo '<h2>Added</h2>' ;
}else {
echo '<h2>not Added</h2>' ;
}
}
It always show added, every time I run it plus a warning saying
Warning: array_unshift() expects parameter 1 to be array
Warning: in_array() expects parameter 2 to be array
What I exactly wanna do is, initially add all 10 article to $post_array and then add only new/unique article to $post_array in the beginning. And display 10 items from $post_array.
Also, I do no think I could achieve what I want through this.
Please advice.
Seems rather redundant:
if (!in_array($Info[$key]->postId, $post_array)){
at the point you run this, $post_array is already the same value as $Info[$key], because your foreach is:
foreach ($Info AS $key => $post_array){
Assuming those $Info[$key] values are sub-arrays, then your in_array call is backwards, the syntax is
in_array($array, $value_to_find)
but you're doing
in_array($value_to_find, $array);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.