I have a multidimensional array and I need to be able to replace JSON placeholders with the relevant value.
Also I need to be able to cascade the values too.
I'm probably just missing a simple thing but its been bugging me for days now.
I'd me very greatful if someone could point out a fix for me.
For example this is my data array:
$SCREEN = array(
'z5OrfqifU8RiA' =>
array(
'current_status' => 'Completed',
'email' => 'luke#test.com',
'Messages' =>
array(
array(
array(
'type' => 'message',
'messageIndex' => 0,
'ReceivedAt' => '17/11/2017 17:06:23',
'Name' => 'Luke ',
'Message' => 'Hello.'
),
array(
'type' => 'message',
'messageIndex' => 1,
'ReceivedAt' => '17/11/2017 17:06:25',
'Name' => 'Luke2 ',
'Message' => 'Hello back.'
)
)
),
'Message Count' => 2,
)
);
I need to take the placeholders that represent the array values as dot notation and replace them with the correct string OR child array using a wildcard.
Here are a few examples of before and afters...
From this:
{ "Messages": "{{SCREEN.Messages}}"}
To:
{
"Messages": [
{
"type": "message",
"messageIndex": 0,
"ReceivedAt": "17/11/2017 17:06:23",
"Name": "Luke",
"Message": "Hello."
},{
"type": "message",
"messageIndex": 1,
"ReceivedAt": "17/11/2017 17:07:06",
"Name": "Luke2",
"Message": "Hello back."
}
]
}
From this:
{ "email": "{{SCREEN.email}}"}
To:
{ "email": "luke#test.com"}
From this:
{ "everything": "{{SCREEN.*}}"}
To:
{
"everything": {
"z5OrfqifU8RiA": {
"current_status": "Completed",
"email": "luke#test.com",
"Messages": [
[
{
"type": "message",
"messageIndex": 0,
"ReceivedAt": "17/11/2017 17:06:23",
"Name": "Luke",
"Message": "Hello."
},
{
"type": "message",
"messageIndex": 1,
"ReceivedAt": "17/11/2017 17:07:06",
"Name": "Luke2",
"Message": "Hello back."
}
]
],
"Message Count": 2
}
}
}
This is the current code that works if you explicitly target a value but not for an array using a wildcard to get anything that is a child to that key.
$SCREEN = array(
'z5OrfqifU8RiA' =>
array(
'current_status' => 'Completed',
'email' => 'luke#test.com',
'Messages' =>
array(
array(
array(
'type' => 'message',
'messageIndex' => 0,
'ReceivedAt' => '17/11/2017 17:06:23',
'Name' => 'Luke ',
'Message' => 'Hello.'
),
array(
'type' => 'message',
'messageIndex' => 1,
'ReceivedAt' => '17/11/2017 17:06:25',
'Name' => 'Luke2 ',
'Message' => 'Hello back.'
)
)
),
'Message Count' => 2,
)
);
$X = parseVariables('{ "everything": "{{SCREEN.*}}"}');
$Y = parseVariables('{ "email": "{{SCREEN.email}}"}');
function parseVariables($array) {
GLOBAL $SCREEN;
foreach(flatten($SCREEN) AS $K => $V)$array = MD_ArrayFandR("{{SCREEN.".$K."}}",$V,$array);
return $array;
}
function flatten($array) {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $key . '.');
} else {
$result[$key] = $value;
}
}
return $result;
}
function MD_ArrayFandR($Find, $Replace,$Array){
if (is_array($Array)){
$ex=json_encode($Array);
return json_decode(str_replace($Find, $Replace,$ex),true);
} else {
return str_replace($Find, $Replace,$Array);
}
}
print_r($X);
print_r($Y);
Write a recursive function that can descend into the structure, like:
function recurse($foo) {
foreach( $foo as $key => $value ) {
if( is_array($value) ) {
$foo[$key] = recurse($value);
} else if( /* $value is a placeholder */ ) {
$foo[$key] = /* replacement */;
}
}
return $foo
}
Related
I am working on combining the array into a key with the count of repeated "option""code". My Request JSON is like this
[{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
},
{
"code": "HIGLIGT_OPTION_HANDLE1"
}
]
},
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
}]
After combing the "productID" and the count of ["options"]["code"] (For ProductId - DENSUS-MARK, the code "HIGLIGT_OPTION_HANDLE" count is 2. So I am getting a output like this.
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 2
},
{
"code": "HIGLIGT_OPTION_HANDLE1",
"count": 1
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 1
}
]
}
}
This is my current php code and I need to optimize & simply this below code
$datas = json_decode($arr,true);
$formattedData = [];
foreach ($datas as $f) {
foreach ($f['options'] as $option) {
$formattedData[$f['productID']]['productID'] = $f['productID'];
$formattedData[$f['productID']]['options']['code'][$option['code']][] = $option['code'];
}
}
foreach ($formattedData as &$data) {
$formattedOptions = [];
foreach ($data['options']['code'] as $key => $codes) {
$formattedOptions[] = [
'code' => $key,
'count' => count($codes)
];
}
$data = $formattedOptions;
}
print_r($formattedData);
Someone, could you please help me in this.
I don't know if this is the optimization you want. Meanwhile, less than two loops, I have not found. It's not quite the expected result, but you should be able to fix it if you need to.
With:
$input = array (
0 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
1 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE1',
),
),
),
1 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
),
2 =>
array (
'productId' => 'DENSUS-MARK-II',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
)
);
Then just:
$result = [];
foreach($input as $row) {
foreach($row['options'] as $value) {
$result[$row['productId']][$value['code']] ??=0;
$result[$row['productId']][$value['code']] += count($value);
}
}
var_export($result);
Results:
array (
'DENSUS-MARK' =>
array (
'HIGLIGT_OPTION_HANDLE' => 2,
'HIGLIGT_OPTION_HANDLE1' => 1,
),
'DENSUS-MARK-II' =>
array (
'HIGLIGT_OPTION_HANDLE' => 1,
),
)
I have an application that retrieves data from a mysql database and generates a json output with php to send to a plugin.
I'm generating the following json output from php:
{
"mapwidth":"1300",
"mapheight":"1000",
"categories":"[]",
"levels":{
"id":"lots",
"title":"Lots",
"map":"maps\/lot-map.svg",
"minimap":"",
"locations":[
{
"id":"lot1",
"title":"Lot 1",
"pin":"hidden",
"description":"<p>Status: <b style=\\\"color: #8eba5e;\\\">Available<\/b><br>Size:\u00a0<b>850 sqm<\/b><br>Please get in touch for an Offer.<\/p>",
"link":null,
"x":"0.4849",
"y":"0.4629",
"fill":null,
"category":"false",
"action":"tooltip"
}
]
},
"maxscale":"1.8"
}
But the format is incorrect. Should be like the following tested json file:
{
"mapwidth": "1300",
"mapheight": "1000",
"categories": [],
"levels": [
{
"id": "lots",
"title": "Lots",
"map": "maps/lot-map.svg",
"minimap": "",
"locations": [
{
"id": "lot12",
"title": "Lot 12",
"pin": "hidden",
"description": "<p>Status: <b style=\"color: #8eba5e;\">Available</b><br>Size: <b>850 sqm</b><br>Please get in touch for an Offer.</p>",
"link": "#more",
"x": "0.3726",
"y": "0.4565"
}
]
}
],
"maxscale": 1.8
}
The difference is in the "levels" key.
This is my php code:
$results = array(
'mapwidth' => '1300',
'mapheight' => '1000',
'categories' => '[]'
);
$results['levels'] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
if ($lotes)
{
// build usable array
foreach($lotes['results'] as $lote)
{
$results['levels']['locations'][] = array(
'id' => $lote['slug'],
'title' => $lote['title'],
'pin' => $lote['pin'],
'description' => $lote['description'],
'link' => $lote['link'],
'x' => $lote['position_x'],
'y' => $lote['position_y'],
'fill' => $lote['fill'],
'category' => $lote['category'],
'action' => $lote['action']
);
}
}
else
$results['error'] = lang('core error no_results');
$results['maxscale'] = '1.8';
// display results using the JSON formatter helper
display_json($results);
Any suggestions? Thanks
You need to make the levels a multidimensional array.
$results['levels'] = array();
$results['levels'][0] = array(
'id' => 'lots',
'title' => 'Lots',
'map' => 'maps/lot-map.svg',
'minimap' => ''
);
Then when you append to do, do it as follows:
$results['levels'][0]['locations'][] = array(
I would like in php to stop duplicate messages by logging msgid to a text file using something like this file_put_contents("a.txt", implode(PHP_EOL, $array1), FILE_APPEND);
and then converting it back to an array using $array1 = file("a.txt"); I would also like to delete messages from the array if they are from a set name
I know how to convert json to an array $array1 = json_decode($json, true);
Json Reply from an api that I cannot control
{
"API": "Online",
"MSG": [
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
},
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
}
]
}
Hi use the following code, first test it out accordingly
$uniqueMessages = unique_multidim_array($messages,'msg');
Usage : Pass the key as the 2nd parameter for which you need to check the uniqueness of array.
<?php
/* Function to handle unique assocative array */
function unique_multidim_array($array, $key) {
/* temp array to hold unique array */
$temp_array = array();
/* array to hold */
$i = 0;
/* array to hold the key for unique array */
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$messages = array(
0 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
),
1 => array(
'info' => array(
'name' => 'example 1'
),
'msg' => 'example 1',
'msgid' => 'example 1'
),
3 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
)
);
echo '<pre>';
echo '*****************BEFORE***********************<br/>';
var_dump($messages);
echo '*****************AFTER***********************<br/>';
$uniqueMessages = unique_multidim_array($messages,'msg');
var_dump($uniqueMessages);
This works for me this is an modded function click here for original function
function RemoveElementByArray($array, $key, $seen){
foreach($array as $subKey => $subArray){
if(in_array($subArray[$key], $seen)){
unset($array[$subKey]);
}
}
return $array;
}
Example:
$array = array(
array("id" => "1", "name" => "example1"),
array("id" => "2", "name" => "example2"),
array("id" => "3", "name" => "example3"));
$SeenArray = array("1", "2");
print_r(RemoveElementByArray($array, "id", $SeenArray));
Result:
Array
(
[2] => Array
(
[id] => 3
[name] => example3
)
)
I need to "reformat" some data coming from an external API so it works with the nested list module of Sencha touch. I cannot change the data output of that external API. Here's an example of the data I get from the API:
$quest = array(
'gastronomy' => [
'restaurants' => [
'italians' => [
[
'title' => 'Al Castello',
'leaf' => true
],
[
'title' => 'Italia',
'leaf' => true
]
],
'asians' => [
[
'title' => 'Gautam',
'leaf' => true
],
[
'title' => 'Wok',
'leaf' => true
]
]
]
]
);
In order to make it work with sencha touch the data must look like this after "reformatting" it with a PHP Service:
$result = array(
'items' => [
[
'title' => 'gastronomy',
'items' => [
[
'title' => 'restaurants',
'items' => [
[
'title' => 'italians',
'items' => [
[
'title' => 'Al Castello',
'leaf' => true
],
[
'title' => 'Italia',
'leaf' => true
]
]
],
[
'title' => 'asians',
'items' => [
[
'title' => 'Gautam',
'leaf' => true
],
[
'title' => 'Wok',
'leaf' => true
]
]
]
]
]
]
]
]
);
I have tried every way I could think of but with no success. What really bugs me is that all keys must be renamed to items. (It's hard for me to access the deeper nested items because of that when I'm using a recursive function)
Haven't tested it, but it seems like a fairly simple recursive function should handle it.
For example:
function parseApi($arr) {
$result = array();
foreach ($arr as $key => $value) {
if (isset($value['leaf'])) {
$result[] = $value;
} else {
$result[] = array(
'title' => $key,
'items' => parseApi($value)
);
}
}
return $result;
}
$result = array( 'items' => $parseApi($quest);
You need a recursive function, and it needs to be able to tell the difference between associative and numerically-indexed arrays.
// from: http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
function isAssoc($arr) { return array_keys($arr) !== range(0, count($arr) - 1); }
function itemize($foo) {
$output = [];
if( ! isAssoc($foo) ) {
foreach( $foo as $value ) {
if( is_array($value) ) {
$output[] = itemize($value);
} else {
$output[] = $value;
}
}
} else {
foreach( $foo as $key => $value ) {
if( is_array($value) ) {
$output[] = [
'title' => $key,
'items' => itemize($value)
];
} else {
$output[$key] = $value;
}
}
}
return $output;
}
echo json_encode(itemize($quest), JSON_PRETTY_PRINT);
Output:
[
{
"title": "gastronomy",
"items": [
{
"title": "restaurants",
"items": [
{
"title": "italians",
"items": [
{
"title": "Al Castello",
"leaf": true
},
{
"title": "Italia",
"leaf": true
}
]
},
{
"title": "asians",
"items": [
{
"title": "Gautam",
"leaf": true
},
{
"title": "Wok",
"leaf": true
}
]
}
]
}
]
}
]
I want delete duplicate post from array of facebook graph data
my page data like :
{
"data": [
{
"link": "http://example.com/188",
"id": "427801497327797_428375477270399",
"created_time": "2013-06-29T14:16:26+0000"
},
{
"link": "http://example.com/188",
"id": "427801497327797_428375187270428",
"created_time": "2013-06-29T14:15:27+0000"
},
{
"link": "http://example.com/188",
"id": "427801497327797_428363873938226",
"created_time": "2013-06-29T13:33:17+0000"
},
{
"link": "http://example.com/196",
"id": "427801497327797_428363597271587",
"created_time": "2013-06-29T13:32:07+0000"
}
],
"paging": {
"previous": "",
"next": ""
}
}
You can see duplicate link example.com/188.
I want get id of all duplicate link.
I'm working with facebook-page-poster
If your concern is to remove duplicate link data then you can do like this
<?php
$duplicate_ids = array();
$all_links = array();
$facebook_data = array(
'data' => array(
array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428375477270399',
'created_time' => '2013-06-29T14=>16=>26+0000'
), array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428375187270428',
'created_time' => '2013-06-29T14=>15=>27+0000'
), array(
'link' => 'http=>//site.com/188',
'id' => '427801497327797_428363873938226',
'created_time' => '2013-06-29T13=>33=>17+0000'
), array(
'link' => 'http=>//site.com/196',
'id' => '427801497327797_428363597271587',
'created_time' => '2013-06-29T13=>32=>07+0000'
)
),
'paging' => array(
'previous' => '',
'next' => ''
)
);
$data_count = count($facebook_data['data']);
for ($i = 0; $i < $data_count; $i++) {
if (in_array($facebook_data['data'][$i]['link'], $all_links)) {
$duplicate_ids[] = $facebook_data['data'][$i]['id'];
unset($facebook_data['data'][$i]);
} else {
$all_links[] = $facebook_data['data'][$i]['link'];
}
}
echo '<pre>'; print_r($duplicate_ids); '</pre>';