How to get array index number by specific value - php

I have an array
Its a json data.
"score":[
{
"userId":"5",
"playtime":"1396369254",
"score":"25"
},
{
"userId":"3",
"playtime":"1396369246",
"score":"2"
},
{
"userId":"1",
"playtime":"1396369056",
"score":"12"
},
{
"userId":"2",
"playtime":"1396369240",
"score":"100"
}
],
I want to print array index number which userId value is 1.

Use a foreach as such:
foreach($array as $key=>$value) {
if($value['userId'] == 1) {
print $key;
break;
}
}

Related

Fragmenting incoming data with PHP Json

The form of the incoming json data:
{
"statusCode": 200,
"message": "success",
"result": [
{
"longitude": -87.06687,
"start_location_latitude": 20.63589,
"start_location_longitude": -87.06687,
"end_location_latitude": 20.63589,
"end_location_longitude": -87.06687,
"highlights": [
{
"title": "Oh Yes...Mezcal Shots",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpg"
},
{
"title": "Playa Del Carmen Beachfront",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpg"
},
{
"title": "Visit the Market",
"url": "https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg"
}
]
}
]
}
This incoming data is combined into a single line.
https://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Mezcal_Shot.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen-Beach_Punta_Esmeralda.jpghttps://phoenix-cdn.azureedge.net/phoenix-blob-public-exps/1396_Playa_Del_Carmen.jpg
But what I want to do is to get the first 4 of these data, for example, by throwing them into separate variables and using them. However, I was never able to do that.
My code:
foreach($UnlockData as $highlights)
{
foreach($highlights as $SingleImage)
{
if(strlen($SingleImage['url']) > 3) {
echo $SingleImage['url'];
}
}
}
This will return the first 4 highlights from each entry in result. I am using the json object vs array because I find using it as objects makes for easier to read code.
<?php
$json = json_decode($incomingJSON);
foreach ($json->result as $result) {
$ctr = 0 ;
foreach($result->highlights as $highlight) {
if (strlen($highlight->url) < 5) continue;
echo "<P>" . $highlight->title. " - " . $highlight->url;
$ctr ++;
if ($ctr>3) break;
}
}
If there is ever only one result then just get all the url from highlights (not clear why the strlen):
$urls = array_column($array['result'][0]['highlights'], 'url');
foreach($urls as $url) {
if(strlen($url) > 3) {
echo $url;
}
}
If there are multiple result then get all the highlights and then get all the url from that:
$urls = array_column(array_column($array['result'], 'highlights'), 'url']);

PHP need to count how many instaneces of specific value in array

I have a JSON file which structure looks like this (very simplified):
[
{
"customerId": "M12345",
"houses": [
{
"id": "OBJ12345_1731321200",
"status": {
"id": "4",
"name": "Sold"
}
],
"plots": [
{
"id": "OBJ12345_1771637082",
"status": {
"id": "4",
"name": "Sold"
}
],
"projects": [],
"farms": [],
"commercialPropertys": [],
"condominiums": [],
"foreignProperties": [],
"premises": []
}
]
I have figured out how to count how many "houses" or "plots" there is:
$content = file_get_contents('estateList/estateList.json');
$GetEstateList = json_decode($content);
count($GetEstateList[0]["houses"]);
count($GetEstateList[0]["plots"]);
BUT Trying to figure out using php how to count how many objects which have a condition status(id:4)
I think you will need to use a loop in order to count the objects, i would use a foreach loop, bellow is an example :
$count = 0;
foreach ( $GetEstateList[0] as $key => $value){
if (isset($value['status']) && $value['status']['id'] === "4") {
$count++;
}
}
First, you need to enter the GetEstateList array, then you need to do a cycle for each type (for now types showed are plots and houses), then you need another cycle, because each type is an array of elements and can have more than one estate.
So, try this code:
// Counter variable for condition expressed after (status == 4)
$counter = 0;
// Enter the array and get `customerId`, `houses` and `plots`,
// but we only need the types of estate, so only `houses` and `plots`, in this case
foreach ( $GetEstateList as $estate_array => $array_attr ) {
// We only need `houses` and `plots` (increasing algorithm performance)
if ( $array_attr == "houses" || $array_attr == "plots" ) {
// We're checking all types of estates (all `houses` and all `plots`)
foreach ( $array_attr as $type => $parameter ) {
// So, we can get `status` of every estate
if ( $parameter == "status") {
// And finally we can get `id` for each estate `status`
if ( $parameter["id"] == "4" ) {
$counter++;
}
}
}
}
}
Notice: the code above cannot work if the written JSON structure is too different from the original.
I figured it out myself...
Maybe not the "correct" way but it works! :)
Feel free to comment on any improvement or modifications...
$StatusCount = 0;
foreach ($GetEstateList[0] as $GetEstateType) {
foreach ($GetEstateType as $GetEstate) {
if ($GetEstate["status"]["id"] == "4") {
$StatusCount++;
}
}
}

php in array not working for dynamicaly array

I am trying to print "Backed" when user id is in array.
Here is my code:
$backId = app()->user->model()->id;
$backers = MProjectBacker::model()->findAll('projectId=:pid', array(':pid' => $data->id));
foreach ($backers as $b) {
if (in_array($backId, $b, true)) {
echo "Backed!";
} else {
echo "Not Backed!";
}
}
But no result and no error.
"If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack."
But why use in_array function to this?
Why dont you just check the field where you store the $backId?
foreach ($backers as $b) {
if ( (int) $b['fieldNameWhereYouStoreTheBackId'] == (int) $backId ) {
echo "Backed!";
}
else {
echo "Not Backed!";
}
}

Looping through category hierarchy

JSON: http://pastebin.com/XjK1VKE3
I need to loop through each category and create a nested list like so:
Electronics(31110)
Mobile & Accessories(31087)
Mobile Accessories(31080)
Cases & Covers(29808)
Screen Guards(729)
Mobile Accessories Combos(355)
Cables(153)
Chargers(21)
Power Banks(9)
Batteries(2)
Selfie Stick(2)
Mobile Lenses(1)
Mobiles(7)
Computers & Accessories(15)
...
...
My code which is starting to get ugly:
if ($object->frontend_filters[0]->values->cats) {
foreach ($object->frontend_filters[0]->values->cats as $cat) {
echo print_r($cat,1);
if ($cat->cats) {
foreach ($cat->cats as $subcat) {
if ($subcat->cats) {
foreach ($subcat->cats as $subcat3) {
$results['categories'][$cat->name][$subcat->name][] = $subcat3->name;
}
}
else {
$results['categories'][$cat->name][] = $subcat->name;
}
}
}
else {
$results['categories'][$cat->name] = [];
}
}
}
How do I do this without creating n number of loops because I'm not sure how many levels deep it might be each time.
Use the following function, see demo here:
// convert your json to a php array
$data = json_decode($yourJson,true);
function doList($data)
{
echo "<ul>";
foreach($data as $i =>$value)
{
if(is_array($value))
{
doList($value);
}
else
{
if($i == 'name' && $value != 'All')
{
echo "<li>$value({$data['count']})</li>";
}
}
}
echo '</ul>';
}
doList($data);

PHP Json object property/value error handling

{
"AFL Round 16":{
"4166082":{
"EventID":4166082,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn To Win 40+",
"Win":"3.00"
}
],
"ActiveCompetitors":1,
"TotalCompetitors":1,
"HasWinOdds":true
},
"EventStatus":"Open"
},
"4167064":{
"EventID":4167064,
"ParentEventID":3744759,
"MainEvent":"North Melbourne v Hawthorn",
"OutcomeDateTime":"2014-07-06 02:00:00",
"Competitors":{
"Competitors":[
{
"Team":"Hawthorn (-5.5)",
"Win":"1.86"
},
{
"Team":"North Melbourne (+5.5)",
"Win":"1.86"
}
],
"ActiveCompetitors":2,
"TotalCompetitors":2,
"HasWinOdds":true
},
"EventStatus":"Open"
}
}
}
I am parsing json objects using PHP and here is a sample of my json. Everything is working fine. I just want to check if object property/value exists if yes then throw errors for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
This is few lines of my code.
$SortedByDate = array();//Sorted By Date Array i.e key=EventID and value=OutcomeDateTime
//Accessing Root Element0
foreach ($json_a as $root_element => $childnode) {
//Accessing child elements
foreach( $childnode as $cKey => $subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' and is_array($subChild['Competitors']['Competitors']) and count ($subChild['Competitors']['Competitors']) == 2 and $OutcomeDateTime_UTC>=$NewDateTime and !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];;
}
}
}
I tired to add if(isset($subChild['OutcomeDateTime']) || is_null($subChild['OutcomeDateTime'])) to check if property name is OutcomeDateTime and it is not null and change json proerty's value (OutcomeDateTime) to null but i get an error that "Invalid argument supplied for foreach()"
is there a better way to check property/values before parsing???
Try this and see if it does what you mean. If not, I don't understand. If it does solve your problem I'll explain why...
//Accessing Root Element0
foreach ($json_a as $root_element => &$childnode) {
//Accessing child elements
foreach( $childnode as $cKey => &$subChild) {
$OutcomeDateTime_UTC=gmdate('Y-m-d H:i:s', strtotime($subChild['OutcomeDateTime']));
//checking ParentEventID=0 , Competitors array = 2 and OutcomeDateTime is greater than current time + 10 min
if($subChild['ParentEventID']=='0' && is_array($subChild['Competitors']['Competitors']) && count ($subChild['Competitors']['Competitors']) == 2 && $OutcomeDateTime_UTC>=$NewDateTime && !preg_match('/\(Live\)/',$subChild['MainEvent']) ) {
//Inserting values into array
$SortedByDate[$cKey] = $subChild['OutcomeDateTime'];
}
if(isset($subChild['OutcomeDateTime']) && !is_null($subChild['OutcomeDateTime'])) {
$subChild['OutcomeDateTime'] = null;
}
}
}
I just want to check if object property/value exists if yes then throw errors
Your wording doesn't make sense and little bit odd, maybe you were saying that you want to validate each key (if they exist) and if each value of those keys are not null
for example i want to check EventID, ParentEventID, OutcomeDateTime, Team (inside Competitors array) are valid property name and they are not null.
Here is a fiddle. Try to remove some elements inside the json string to check: Fiddle
$json_a = '{ "AFL Round 16":{ "4166082":{ "EventID":4166082, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn To Win 40+", "Win":"3.00" } ], "ActiveCompetitors":1, "TotalCompetitors":1, "HasWinOdds":true }, "EventStatus":"Open" }, "4167064":{ "EventID":4167064, "ParentEventID":3744759, "MainEvent":"North Melbourne v Hawthorn", "OutcomeDateTime":"2014-07-06 02:00:00", "Competitors":{ "Competitors":[ { "Team":"Hawthorn (-5.5)", "Win":"1.86" }, { "Team":"North Melbourne (+5.5)", "Win":"1.86" } ], "ActiveCompetitors":2, "TotalCompetitors":2, "HasWinOdds":true }, "EventStatus":"Open" } }}';
$json_a = json_decode($json_a, true);
$json_a = reset($json_a); // ignore these parts since you already know how to get them
$errors = array();
$valid_keys = array('EventID', 'ParentEventID', 'OutcomeDateTime', 'MainEvent', 'Competitors', 'EventStatus');
foreach($json_a as $event_id => $values) {
// check for keys
$keys = array_keys($values);
foreach($valid_keys as $key) {
if(!in_array($key, $keys)) {
// check keys, not valid if it goes here
$errors[] = "<b>$key</b> is missing on your data <br/>";
} else {
// valid keys, check values
if(empty($values[$key])) {
// empty values
$errors[] = "<b>$key</b> has an empty value <br/>";
}
}
}
// next checking, competitors
foreach($values['Competitors']['Competitors'] as $competitors) {
if(empty($competitors)) {
// if competitors is empty
$errors[] = "<b>Competitors</b> has an empty value <br/>";
}
}
}
if(!empty($errors)) {
// not a good error triggering device, just change this to something else
trigger_error('<pre>'.implode($errors).'</pre>', E_USER_ERROR);
}

Categories