I have two arrays,one containing a list of names (array name = canNAMES),
["name 1","name 2","name 3"];
the first array has around 70 values within, And my second array has around 600 objects within it (array name=data),
[
{
"agency": "test agency",
"work_end": "21-Oct",
"contractor": "name n",
"rate": "£30.00",
"hours": 32,
"exp": null,
"net": "£960.00",
"vat": "£192.00",
"gross": "£1,152.00"
},
{
"agency": "test agency",
"work_end": "21-Oct",
"contractor": "name n",
"rate": "£25.00",
"hours": 30,
"exp": null,
"net": "£750.00",
"vat": "£150.00",
"gross": "£900.00"
}
]
I am trying to use php in_array function to get the objects that has the names listed in the first array out.
when I use it as below I am able to get the required results but it only reads up-to 70 records
foreach ($canNAMES as $index => $row) {
if (in_array($row, (array) $data[$index]["contractor"])) {
$MAIN[] = $data[$index];
}
}
The above code is where i loop through the first array(canNAMES array) that has 70 records. when i try looping through the second array(data array) i get an undefined offset error as the first array doesn't have a index above 69.
My question is how to solve this issue, is there a better way to do what i am trying.
Thanks
If the names aren't unique then you can easily just loop through each sets of data matching one against the other...
$canNAMES = ["name 1","name 2","name 3"];
$data = json_decode ('[
{
"agency": "test agency",
"work_end": "21-Oct",
"contractor": "name 3",
"rate": "£30.00",
"hours": 32,
"exp": null,
"net": "£960.00",
"vat": "£192.00",
"gross": "£1,152.00"
},
{
"agency": "test agency",
"work_end": "21-Oct",
"contractor": "name 1",
"rate": "£25.00",
"hours": 30,
"exp": null,
"net": "£750.00",
"vat": "£150.00",
"gross": "£900.00"
}
]');
foreach ( $canNAMES as $name ) {
foreach ( $data as $entry ) {
if ( $name == $entry->contractor ) {
print_r($entry);
}
}
}
I guess you want all the element in the data array that have a name that exist in the canNAMES array.
Consider the following:
$canNAMES = ["ccc","bbb","eee"];
$data = json_decode('[{"id":1, "contractor": "aaa"}, {"id":2, "contractor": "ddd"}, {"id":3, "contractor": "ccc"}, {"id":4, "contractor": "bbb"}]');
$res = array();
foreach($data as $elem) {
if (in_array($elem->contractor, $canNAMES))
$res[] = $elem;
}
echo print_r($res);
return;
Related
hello i have json file which contain like this data
{
"data": [
{
"SN": "210477",
"name": "jane",
"stdcode": "446515",
"total": 611
},
{
"SN": "210474",
"name": "JOHN doe",
"stdcode": "446512",
"total": 610
},
{
"SN": "210475",
"name": "smith doe",
"stdcode": "446513",
"total": 610
},
{
"SN": "210476",
"name": "omar",
"stdcode": "446514",
"total": 610
}
]
}
as you can see there is duplicate in total in the last three data in total which is 610
i want to order this data according to "total" so it be printed like this
1.jane
2.JOHN doe
2.smith doe
2.omar
i have this code that order it but this not what i want
<?php
$get_records = #file_get_contents('./result.json',true);
$decode_records = json_decode($get_records);
$data = $decode_records->data;
usort($data, function($a, $b) {
return $a->total > $b->total ? -1 : 1;
});
for($x=0;$x<=count($data);$x++){
echo $x+1 .".".$data[$x]->name;
}
?>
the code output
1.jane
2.JOHN doe
3.smith doe
4.omar
Check whether the total has changed, and don't increment the rank if not.
$rank = 0;
$last_total = null;
foreach ($data as $d) {
if ($d->total !== $last_total) {
$rank++;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}
Note that this means that the next index after all the duplicates will be ranked #3. If you want it to jump to 5 you need to use the array index as well.
$last_total = null;
foreach ($data as $i => $d) {
if ($d->total !== $last_rank) {
$rank = $i+1;
$last_total = $d->total;
}
echo "$rank. {$data->name}<br>";
}
I have two JSON files of same format, forexample
1st JSON File
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 1,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "Joe Biden",
"email": "joe#mail.com"
}
},
{
"node": {
"id": "QnVzaW5lc3M6Z",
"name": "MULTIMEDIA PLUMBUM",
"email": "mdi#mail.com"
}
}
]
}
}
}
}
2nd JSON file
{
"data": {
"business": {
"id": "3NzA0ZDli",
"customers": {
"pageInfo": {
"currentPage": 2,
"totalPages": 695,
"totalCount": 1389
},
"edges": [
{
"node": {
"id": "QnVzaW7dQ8N",
"name": "Mark",
"email": "mark#mail.com"
}
},
{
"node": {
"id": "QnVzaW5l5Gy9",
"name": "Trump",
"email": "trump#mail.com"
}
}
]
}
}
}
}
Each user has a unique "id", I want to get their id by searching their name in php, how can I do this
This is my PHP script
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
foreach ($result2 as $k => $v) {
if ($v['data']['business']['edges']['customers']['node']['name'] == "Trump") break;
}
echo $result[$k]['data']['business']['edges']['customers']['node']['name']; //I want to get id for trump "QnVzaW5l5Gy9"
Each user has a unique "id", I want to get their id by searching their name in php. How can I get id by searching name in both files at a time?
Thanks
Since you are looping through json file it will search inside of "data" so you can't use $v['data']
Also since edges is also array that have same values and you want to search inside of it you must make loop on that also
Here is example
foreach ($result2 as $k => $v) {
foreach ($v['business']['customers']['edges'] as $val) {
if ($val['node']['name'] == 'Trump') {
echo '<pre>';
// and now you can access any of those values, echo $val['node']['id'];
print_r($val['node']);
echo '</pre>';
}
}
}
Output
Array
(
[id] => QnVzaW5l5Gy9
[name] => Trump
[email] => trump#mail.com
)
EDIT
Since you want to search in both files at a same time you can put them into array and then use it like this
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$joined_result = array($result1, $result2);
foreach($joined_result as $val) {
// this will take all nodes where you will search
$node = $val['data']['business']['customers']['edges'];
foreach ($node as $value) {
if ($value['node']['name'] == 'Trump') {
echo '<pre>';
print_r($value['node']);
echo '</pre>';
}
}
}
You have two questions there, no?
The first question I get is "How to get the ID for a certain name"
$node = $result2['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
Almost your code, but I echo the ID when the name matches "Trump".
The second question I see is "How do search both json data at once"
$json1 = file_get_contents("1.json");
$json2 = file_get_contents("2.json");
$result1 = json_decode($json1, true);
$result2 = json_decode($json2, true);
$all_data = [$result1, $result2];
foreach($all_data as $data) {
$node = $data['data']['business']['customers']['edges']['node'];
if ($node['name'] == "Trump") echo $node['id'];
}
Transforming both json data to be in an array and then simply looping over the whole array should do the trick.
I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}
suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>