PHP in_array() not working properly - php

I have an if statment below that checks if a value is present in an array and adds it in there if it's not.
Apparently even if the value is in the array, it triggers it again.
As far as I understand, it should only display 1 of each value, because it will only trigger 3 times, like this:
Digital Photography -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
The code:
if (!in_array($unit['course_name'], $courseList)) {
$courseList[$unit['course_name']]['name'] = $unit['course_name'];
$courseList[$unit['course_name']]['seconds'] = 0;
echo $courseList[$unit['course_name']]['name'] . ' -> ' . $courseList[$unit['course_name']]['seconds'];
echo "<BR>";
}
But it outputs:
Digital Photography -> 0
Step by Step Macintosh Training -> 0
Step by Step Macintosh Training -> 0
Step by Step Macintosh Training -> 0
How to become a Powerful Speaker -> 0
How to become a Powerful Speaker -> 0
Here is the var_dump($unit):
array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(19) "Digital Photography" [1]=> string(19) "Digital Photography" ["unit_id"]=> string(3) "181" [2]=> string(3) "181" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "227" [2]=> string(3) "227" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "231" [2]=> string(3) "231" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
array(8) { ["author_name"]=> string(15) "William Merussi" [0]=> string(15) "William Merussi" ["course_name"]=> string(31) "Step by Step Macintosh Training" [1]=> string(31) "Step by Step Macintosh Training" ["unit_id"]=> string(3) "233" [2]=> string(3) "233" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(32) "How to become a Powerful Speaker" [1]=> string(32) "How to become a Powerful Speaker" ["unit_id"]=> string(4) "1080" [2]=> string(4) "1080" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
array(8) { ["author_name"]=> string(10) "tuiuiu_dev" [0]=> string(10) "tuiuiu_dev" ["course_name"]=> string(32) "How to become a Powerful Speaker" [1]=> string(32) "How to become a Powerful Speaker" ["unit_id"]=> string(4) "1084" [2]=> string(4) "1084" ["unit_quantity"]=> string(1) "1" [3]=> string(1) "1" }
Thank you for any help!

in_array() method check array values, not keys. From your example I can see that as value you have an array with name and seconds fields.
I think you want to check if that id exists in your array.
So this if:
if (!in_array($unit['course_name'], $courseList)) {
Should be change like this:
if (!isset($courseList[$unit['course_name']])) {
This way you check if the $unit['course_name'] is in your array as key.

If you have an array with only values you should use in_array function as this example:
$array = array("A", "B", "C");
in_array($string, $array) ? "found" : "not found";
Else if you have an array with keys you should use isset function as this example:
$array = array("A" => "Result A", "B" => "Result B", "C" => "Result C");
isset($array[$string]) ? "found" : "not found";

Related

Merge array where duplicate in multidimensional array

I've been trying to merge this array ONLY WHERE $array[4] exists more than one time, example: $array[4] == 'red' exactly twice. How can I merge only those arrays while keeping the others? I have made several attempts at this and I am willing to include my efforts if asked.
Consider this array:
array(3) {
[0]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(1) "2"
[3]=>
string(9) "Domain(s)"
[4]=>
string(20) "red"
}
[1]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(20) "red"
}
[2]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "536"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(16) " University Test"
}
}
TRYING TO ACHIEVE:
array(3) {
[0]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "532"
[2]=>
string(1) "2"
[3]=>
string(9) "Domain(s)"
[4]=>
string(20) " red"
[5]=>
string(3) "Fee"
[6]=>
string(7) "License"
}
[1]=>
array(5) {
[0]=>
string(3) "UID"
[1]=>
string(3) "536"
[2]=>
string(7) "License"
[3]=>
string(3) "Fee"
[4]=>
string(16) " University Test"
}
}
foreach ($test as $item) {
if (!isset($merged[$item[4]])) {
// add the item to the merged array using key=$item[4]
$merged[$item[4]] = $item;
} else {
// merge the item with the item that is already in the array at key=$item[4]
$merged[$item[4]] = array_unique(array_merge($merged[$item[4]], $item));
// array_unique is necessary because array_merge will not overwrite numeric keys
}
}
// convert the keys back to numeric (if you care to)
$merged = array_values($merged);

how do I extract a value from a JSON object Array of Arrays

I am having a hard time extracting a value from the following JSON object
array(3) { [0]=> object(stdClass)#1 (11) { ["Group"]=> string(2) "18" ["GroupName"]=> string(8) "Wireline" ["Region"]=> string(2) "15" ["RegionName"]=> string(8) "Atlantic" ["Province"]=> string(1) "1" ["ProvinceName"]=> string(13) "New Brunswick" ["City"]=> string(2) "11" ["CityName"]=> string(10) "Campbelton" ["Site"]=> string(2) "37" ["SiteName"]=> string(16) "Campbellton PNCT" ["Year"]=> string(4) "2016" }
[1]=> object(stdClass)#2 (5) { ["PlatformID"]=> string(1) "1" ["PlatformTag"]=> string(6) "Access" ["Rack"]=> string(24) "23" Width 36" Depth Rack" ["RackValue"]=> string(1) "2" ["Comments"]=> string(0) "" }
[2]=> object(stdClass)#3 (12) { ["Rack"]=> string(31) "23" Width 36" Depth Rack Access" ["RackValue"]=> string(1) "2" ["RackComments"]=> string(0) "" ["Manufacturer"]=> string(6) "werwer" ["Name"]=> string(6) "werwer" ["Quantity"]=> string(1) "1" ["RackUnits"]=> string(1) "1" ["Power"]=> string(1) "1" ["ActivePassive"]=> string(6) "Active" ["ACDC"]=> string(2) "AC" ["ConnectivityIDs"]=> array(1) { [0]=> string(1) "2" } ["Connectivity"]=> array(1) { [0]=> string(5) "Fiber" } } }
I am trying to extract each item in a foreach loop within PHP Above is the var_dump of the $data[0] JSON object it demonstrates what the Array item looks like.
My foreach is the following
$data = json_decode($_POST["submitdata"]);
$Forecasts = $data[0];
foreach($Forecasts as $Forecast){
echo($Forecast->PlatformID);}
but it returns nothing as a result. Can someone explain to me how to get this from the second Array in the object?
simply place the Index of the inner array along with the object as shown below. This will check for the sub item for the PlatformID and return it to the screen.
foreach($Forecasts as $Forecast){
echo($Forecast[1]->PlatformID);}

How to get object like value:item:private from PHP Array

I have the array like this:
} ["items":"Jcart":private]=> array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "2"
[2]=>
string(7) "ABC-123" }
How to get the "items" values in a php variable?
///////
Te complete object is:
object(Jcart)#1 (8) {
["config"]=>
array(12) {
["jcartPath"]=>
string(6) "jcart/"
["checkoutPath"]=>
string(12) "checkout.php"
["item"]=>
array(6) {
["id"]=>
string(10) "my-item-id"
["name"]=>
string(12) "my-item-name"
["price"]=>
string(13) "my-item-price"
["qty"]=>
string(11) "my-item-qty"
["url"]=>
string(11) "my-item-url"
["add"]=>
string(13) "my-add-button"
}
["paypal"]=>
array(5) {
["id"]=>
string(38) "seller_1282188508_biz#conceptlogic.com"
["https"]=>
bool(true)
["sandbox"]=>
bool(false)
["returnUrl"]=>
string(0) ""
["notifyUrl"]=>
string(0) ""
}
["currencyCode"]=>
string(3) "USD"
["csrfToken"]=>
bool(false)
["text"]=>
array(14) {
["cartTitle"]=>
string(13) "Shopping Cart"
["singleItem"]=>
string(4) "Item"
["multipleItems"]=>
string(5) "Items"
["subtotal"]=>
string(8) "Subtotal"
["update"]=>
string(6) "update"
["checkout"]=>
string(8) "checkout"
["checkoutPaypal"]=>
string(20) "Checkout with PayPal"
["removeLink"]=>
string(6) "remove"
["emptyButton"]=>
string(5) "empty"
["emptyMessage"]=>
string(19) "Your cart is empty!"
["itemAdded"]=>
string(11) "Item added!"
["priceError"]=>
string(21) "Invalid price format!"
["quantityError"]=>
string(38) "Item quantities must be whole numbers!"
["checkoutError"]=>
string(34) "Your order could not be processed!"
}
["button"]=>
array(4) {
["checkout"]=>
string(0) ""
["paypal"]=>
string(0) ""
["update"]=>
string(0) ""
["empty"]=>
string(0) ""
}
["tooltip"]=>
bool(true)
["decimalQtys"]=>
bool(false)
["decimalPlaces"]=>
int(1)
["priceFormat"]=>
array(3) {
["decimals"]=>
int(2)
["dec_point"]=>
string(1) "."
["thousands_sep"]=>
string(1) ","
}
}
["items":"Jcart":private]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "2"
}
["names":"Jcart":private]=>
array(2) {
[3]=>
string(12) "Hockey Stick"
[2]=>
string(13) "Baseball Mitt"
}
["prices":"Jcart":private]=>
array(2) {
[3]=>
string(5) "33.25"
[2]=>
string(5) "19.50"
}
["qtys":"Jcart":private]=>
array(2) {
[3]=>
string(1) "1"
[2]=>
string(2) "20"
}
["urls":"Jcart":private]=>
array(2) {
[3]=>
string(15) "http://bing.com"
[2]=>
string(16) "http://yahoo.com"
}
["subtotal":"Jcart":private]=>
float(423.25)
["itemCount":"Jcart":private]=>
int(21)
}
I just need the values in ["items":"Jcart":private]
I assume you got this by casting an object to an array. If that's the case, you shouldn't be doing that! The property is private because you're not supposed to access it directly because it's not a public API. The object should have a public method which you're supposed to call instead, that's the public API. Something like $foo->getItems() or such. Read the documentation and/or source code.

removing data from array

I have a problem i need to ignore any array key if it has "lastpost" set to "No Posts"
This is the array dump of $sublast:
array(3) { [0]=> array(9) { ["forum_category_id"]=> string(1) "3" ["name"]=> string(15) "Sub category #1" ["description"]=> string(39) "This is a short description test.... #2" ["topics"]=> string(1) "0" ["lastpost"]=> string(8) "No Posts" ["lastpostauthor"]=> string(1) " " ["lastposturl"]=> string(88) "http://test.codetrove.com/index.php?route=forum/read&forum_path=3&forum_post_id=" ["posts"]=> int(0) ["href"]=> string(81) "http://test.codetrove.com/index.php?route=forum/forum_category&forum_path=1_3" } [1]=> array(9) { ["forum_category_id"]=> string(1) "7" ["name"]=> string(16) "Test sub Sub cat" ["description"]=> string(0) "" ["topics"]=> string(1) "2" ["lastpost"]=> string(26) "Mon Apr 1, 2013 1:00:42 pm" ["lastpostauthor"]=> string(16) "Justine Smithies" ["lastposturl"]=> string(90) "http://test.codetrove.com/index.php?route=forum/read&forum_path=7&forum_post_id=63" ["posts"]=> int(2) ["href"]=> string(81) "http://test.codetrove.com/index.php?route=forum/forum_category&forum_path=1_7" } [2]=> array(9) { ["forum_category_id"]=> string(1) "9" ["name"]=> string(11) "Test cat #3" ["description"]=> string(20) "Short description #3" ["topics"]=> string(1) "2" ["lastpost"]=> string(26) "Mon Apr 1, 2013 1:00:15 pm" ["lastpostauthor"]=> string(16) "Justine Smithies" ["lastposturl"]=> string(90) "http://test.codetrove.com/index.php?route=forum/read&forum_path=9&forum_post_id=62" ["posts"]=> int(2) ["href"]=> string(81) "http://test.codetrove.com/index.php?route=forum/forum_category&forum_path=1_9" } }
Here is the code i am trying to do that only it messes up as it always goes for the top one which is right but i need a way to remove the top entries if the have "lastpost" set to "No Posts" so it get the correct info .
<?php
$sublast = $forum_category['children'];
foreach ($sublast as $key => $row) {
$dates[$key] = $row['lastpost'];
}
array_multisort($dates, SORT_ASC, $sublast);
$lastitem = $sublast[count($sublast) - 1];
var_dump($sublast);
?>
This is the dump of $lastitem :
array(9) { ["forum_category_id"]=> string(1) "3" ["name"]=> string(15) "Sub category #1" ["description"]=> string(39) "This is a short description test.... #2" ["topics"]=> string(1) "0" ["lastpost"]=> string(8) "No Posts" ["lastpostauthor"]=> string(1) " " ["lastposturl"]=> string(88) "http://test.codetrove.com/index.php?route=forum/read&forum_path=3&forum_post_id=" ["posts"]=> int(0) ["href"]=> string(81) "http://test.codetrove.com/index.php?route=forum/forum_category&forum_path=1_3" }
And as you can see it took the "No Posts" when that whole array entry should be removed so it takes array[1] Which is the one i need.
Any ideas please ?
Use unset function in php to delete elements
Unset will do your need.
unset($array)

How should I sort this array?

I'm currently trying to implement a messaging functionality in my system. My goal right now is having a jQuery popup dialog which displays the name of users that have messaged the other person and then clicking on that person's name will show the new messages. I've done the popup dialog bit so my next step is getting and sorting the messages from database.
What I've done now is retrieve the new messages from database. I am unsure of how to proceed as my array of unread messages contains the element of the sender's id more than once. I do not want to loop through my unread messages and then get the same sender id again and again and as such retrieve their details from database again and again.
Here's an example of my array:
array(8) {
[6]=>
array(7) {
["id"]=>
string(2) "52"
["useridfrom"]=>
string(3) "330"
["useridto"]=>
string(3) "139"
["message"]=>
string(10) "test"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336561645"
["messagetype"]=>
string(6) "direct"
}
[7]=>
array(7) {
["id"]=>
string(2) "53"
["useridfrom"]=>
string(3) "330"
["useridto"]=>
string(3) "139"
["message"]=>
string(8) "bye"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336561648"
["messagetype"]=>
string(6) "direct"
}
[1]=>
array(7) {
["id"]=>
string(2) "30"
["useridfrom"]=>
string(3) "329"
["useridto"]=>
string(3) "139"
["message"]=>
string(243) "Hi Bob"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1330942044"
["messagetype"]=>
string(6) "direct"
}
[3]=>
array(7) {
["id"]=>
string(2) "42"
["useridfrom"]=>
string(3) "243"
["useridto"]=>
string(3) "139"
["message"]=>
string(4) "test"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1335517653"
["messagetype"]=>
string(6) "direct"
}
[4]=>
array(7) {
["id"]=>
string(2) "46"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(8) "sdsdfsdf"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336139572"
["messagetype"]=>
string(6) "direct"
}
[5]=>
array(7) {
["id"]=>
string(2) "47"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(13) "8528528285285"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336143958"
["messagetype"]=>
string(6) "direct"
}
array(8) {
[6]=>
array(7) {
["id"]=>
string(2) "52"
["useridfrom"]=>
string(3) "330"
["useridto"]=>
string(3) "139"
["message"]=>
string(10) "test"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336561645"
["messagetype"]=>
string(6) "direct"
}
[7]=>
array(7) {
["id"]=>
string(2) "53"
["useridfrom"]=>
string(3) "330"
["useridto"]=>
string(3) "139"
["message"]=>
string(8) "bye"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336561648"
["messagetype"]=>
string(6) "direct"
}
[1]=>
array(7) {
["id"]=>
string(2) "30"
["useridfrom"]=>
string(3) "329"
["useridto"]=>
string(3) "139"
["message"]=>
string(243) "Hi Bob"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1330942044"
["messagetype"]=>
string(6) "direct"
}
[3]=>
array(7) {
["id"]=>
string(2) "42"
["useridfrom"]=>
string(3) "243"
["useridto"]=>
string(3) "139"
["message"]=>
string(4) "test"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1335517653"
["messagetype"]=>
string(6) "direct"
}
[4]=>
array(7) {
["id"]=>
string(2) "46"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(8) "sdsdfsdf"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336139572"
["messagetype"]=>
string(6) "direct"
}
[5]=>
array(7) {
["id"]=>
string(2) "47"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(13) "8528528285285"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336143958"
["messagetype"]=>
string(6) "direct"
}
[2]=>
array(7) {
["id"]=>
string(2) "10"
["useridfrom"]=>
string(3) "138"
["useridto"]=>
string(3) "139"
["message"]=>
string(54) "Hi Emma thank you for submitting your homework - Jenny"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1309122193"
["messagetype"]=>
string(6) "direct"
}
}
This is what I've done in PHP so far:
$m = new Messaging();
$json = $m->getUnreadMessages($uid);
/** sort messages by useridfrom **/
uasort($json, array($m, 'messageCompare'));
foreach($json as $j)
{
//do sorting of messages here ??
}
echo json_encode($json);
exit;
I guess ideally, I would want to create a new array out of this where the key is useridfrom (sender) and then their messages and then associated with each message the timecreated. What is the best way to do this?
Thanks in advance.
EDIT
As you can see from the array example there are duplicate useridfrom elements where useridfrom = 241 twice. This means that the user 241 has sent two messages, if there were 3 useridfrom 241 elements then that means he/she sent 3 messages. My goal is two group the useridfrom together as keys in an array so there are no duplicates then associated with that key we have all their messages (message) and the time the message was created (timecreated).
[4]=>
array(7) {
["id"]=>
string(2) "46"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(8) "sdsdfsdf"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336139572"
["messagetype"]=>
string(6) "direct"
}
[5]=>
array(7) {
["id"]=>
string(2) "47"
["useridfrom"]=>
string(3) "241"
["useridto"]=>
string(3) "139"
["message"]=>
string(13) "8528528285285"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1336143958"
["messagetype"]=>
string(6) "direct"
}
[1]=>
array(7) {
["id"]=>
string(2) "30"
["useridfrom"]=>
string(3) "329"
["useridto"]=>
string(3) "139"
["message"]=>
string(243) "Hi Bob"
["format"]=>
string(1) "0"
["timecreated"]=>
string(10) "1330942044"
["messagetype"]=>
string(6) "direct"
}
So from this example, it should lead to an array of something like what mariomario has suggested:
array{
['241'] => array(
[0] => array(time=>'time1', message => "hello i am 241"),
[1] => array(time=>'time2', message => "nice to meet you"),
),
['330'] => array(
[0] => array(time=>'time1', message => "hello i am 330"),
[1] => array(time=>'time2', message => "goodbye"),
)
}
EDITED:
After a little pondering I'd do this:
$data = array();
foreach ($json as $j) {
if (!array_key_exists($j['useridfrom'], $data)) {
$data[$j['useridfrom']] = array();
}
if (!array_key_exists($j['useridto'], $data[$j['useridfrom']])) {
$data[$j['useridfrom']][$j['useridto']] = array();
}
$data[$j['useridfrom']][$j['useridto']][] = array(
'message' => $j['message'],
'timestamp' => $j['timecreated']
);
}
Keep your data ordered like so ORDER BY timecreated DESC and that concats everything like you want ordered after the time.
This should net an array like so:
'sender1' => (
'recipient1' = (
(
'message' => 'MESSAGE HERE',
'timecreated' => 'TIME HERE'
),
(
'message' => 'ANOTHER MESSAGE HERE',
'timecreated' => 'ANOTHER TIME HERE'
)
),
'recipient2' = (
(
'message' => 'MESSAGE HERE',
'timecreated' => 'TIME HERE'
)
)
),
'sender2' => (
)
wouldn't you do something like this
$newArray = array()
foreach($json as $j)
{
$array[$j['useridfrom']][] = array('time'=>$j['timecreated'],
'message'=>$j[message]);
}
they you will have a array like this:
array{
['user1'] => array(
[0] => array(time=>'time1', message => message1),
[1] => array(time=>'time2', message => message2),
),
['user2'] => array(
[0] => array(time=>'time1', message => message1),
[1] => array(time=>'time2', message => message2),
)
}
but maybe I am understanding you not correct.
Use array_multisort in PHP:
http://php.net/manual/en/function.array-multisort.php

Categories