PHP get array items based on string mask - php

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;
}

Related

Search item on json object PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have this kind of json objects and im trying to search an item under sales->products->id but i can't make it work. I hope someone could help me. Thanks!
"sales": [
{
"ID": 123456,
"transaction_id": "123456789",
"key": "sdawa57sd547sad4sadx54ad",
"subtotal": 20,
"tax": "0",
"fees": null,
"total": "20",
"gateway": "paypal",
"email": "email#email.com",
"date": "2018-08-01 13:13:55",
"discounts": null,
"products": [
{
"id": 1234,
"quantity": 1,
"name": "Product 1",
"price": 20,
"price_name": ""
}
]
}
This is the code i used:
$content = file_get_contents($url);
$results= json_decode($content, TRUE);
foreach($results->sales as $item)
{
if($item->products->id == "1234")
{
echo $item->products->name;
}
}
Because you've passed the second parameter as true to json_decode, your $results variable is an array, so you need to access it like that:
foreach($results['sales'] as $item) {
foreach ($item['products'] as $product) {
if ($product['id'] == '1234') echo $product['name'];
}
}
Output:
Product 1
Demo on 3v4l.org
If you want to find which sales have the product, then you should do this
$results= json_decode($content);
$productid = "1234"; //product you want to search for
foreach($result->sales as $sale)
{
$keys = array_keys(array_column($sale->products, 'id'), $product_id);
if(!empty($keys))
$saleIDs[] = $sale->ID;
}
var_dump($saleIDs); //contains all the sale IDs that have the product
Read about array_keys and array_column.

php array looping through two arrays with different indexes

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;

How to take a value from nested array(json format) without using multiple foreach in php

I want to take the all id values in the json format.
{
"1": {
"name": "test",
"followup": {
"1": {
"id": "98",
"followup": {
"1": {
"id": "93",
"followup": {
"1": {
"id": "174"
},
}
}
}
}
}
}
}
I can achieve this by using nested foreach. But now the 'followup' key is present in 3 but it may came 6,7 so we can't add 6,7 foreach.
You can use the array_walk_recursive() for this, like(DEMO):
$ids = array();
$data = json_decode($str, true);
array_walk_recursive($data, function($v, $k) use (&$ids) {
if ($k === 'id') {
$ids[] = $v;
}
});
var_dump($ids);
This basically goes through every index 1 at a time and matches the the keys against the key id, and if it matches it captures the value.

Access variable Array Data PHP

i have the following Array Structure from Facebook Graph API response.
"data": [
{
"actions": [
{
"action_type": "comment",
"value": "2"
},
{
"action_type": "offsite_conversion",
"value": "1606"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
{
"actions": [
{
"action_type": "post",
"value": "2"
},
{
"action_type": "post_reaction",
"value": "33"
},
{
"action_type": "page_engagement",
"value": "816"
},
{
"action_type": "post_engagement",
"value": "807"
},
{
"action_type": "offsite_conversion",
"value": "1523"
}
],
"date_start": "2017-04-03",
"date_stop": "2017-05-02"
},
]
The Number of values is flexible and i want to get the value from "offsite_conversion". Normally i would do it for example like that:
data['data'][0]['actions']['1']['value']
But in that case this doesn't work because ['1'] is variable.
Use a loop and test the action type.
foreach ($data['data'][0]['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$result = $data['value'];
break;
}
}
because "offsite_conversions" is always the last
If $data['data'][0]['actions'][LAST VALUE]['value'] is what you're looking for:
Your idea of counting should work then:
$actions = $data['data'][0]['actions'];
$index = count($actions) - 1;
$value = $actions[$index]['value'];
So not completely clear what are you trying to achieve, but in a simple way you can just iterate over your $data array:
$needed_values = array();
foreach ($data['data'] as $item) {
foreach ($item['actions'] as $action) {
if ($action['action_type'] == 'offsite_conversion') {
$needed_values[] = $action['value'];
}
}
}
Barmar has the best approach if you don't know where it is, but it's much easier if you want the last one:
$result = end($data['data'][0]['actions'])['value'];
Pretend $json holds the data from facebook
<?php
$data = json_decode($json);
$conversions = 0;
foreach ($data as $datum) {
foreach ($datum['actions'] as $action) {
if ($action['action_type'] === 'offsite_convserion') {
$conversions += (int)$action['value'];
break;
}
}
}

Replace array keys

i have an array like this JSON Example .I'm trying to replace the numeric key ..."conn":{"1":{"... with string key such as "node".
FOR EXAMPLE i want to create this:
{
"Level": [
{
"main": "472321514",
"main_lat": "39.1057579",
"main_lon": "26.5451331",
"conn": {
"node": {
"id": "599416249",
"coords": {
"lat": "39.1055889",
"lon": "26.5452403"
},
"distance": 0.0209442235276
},...
Before json encoding my script is:
foreach ($ways as $w){
$nd=$w->nd;
foreach ($nd as $w2){
$nodes_Array[]=(string)$w2->attributes()->ref;
}
for($ww=0;$ww<count($nodes_Array);$ww++){
$nodes_Array2[$bb]['main'] = $nodes_Array[$ww];
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['main']){
$nodes_Array2[$bb]['main_lat']= $node_content[$gg]['lat'];
$nodes_Array2[$bb]['main_lon']= $node_content[$gg]['lon'];
}
}
$nodes_Array2[$bb]['conn'] = array_diff($nodes_Array, array($nodes_Array[$ww]));
for($cc=0;$cc<count($nodes_Array2[$bb]['conn']);$cc++){
for($gg=0;$gg<count($node_content);$gg++){
if($node_content[$gg]['id']==$nodes_Array2[$bb]['conn'][$cc]){
$nodes_Array2[$bb]['conn'][$cc]=Array(
'id'=>$node_content[$gg]['id'],
'coords'=>Array(
'lat'=>$node_content[$gg]['lat'],
'lon'=>$node_content[$gg]['lon'],
),
'distance'=>distance($nodes_Array2[$bb]['main_lat'],$nodes_Array2[$bb]['main_lon'],$node_content[$gg]['lat'],$node_content[$gg]['lon'],"K"),
);
}
}
}
$bb++;
}
unset($nodes_Array);
}

Categories