Search for a value in JSON using php - php

I have a JSON file in this format:
[
["name","purpose","description"],
["name2","purpose2","description2"],
["name3","purpose3","description3"]
]
Now, I have got the solutions for finding them by key. But, my JSON doesn't have keys. How can I search inside this JSON object to find second element by using "purpose2"? Also, I need to display the second element (i.e. "name2","purpose2","description2").
I used this function, but it's not helping me out.
function searchJson($obj, $value) {
foreach($obj as $item) {
foreach($item as $child) {
if(isset($child) && $child == $value) {
return $child;
}
}
}
return null;
}
Thanks in advance !

As the json data doesn't have string keys upon which to search you can branch the logic in the function to test for numeric indexes and then use in_array perhaps
$json = '[["name","purpose","description"],["name2","purpose2","description2"],["name3","purpose3","description3"]]';
function searchJson( $obj, $value ) {
foreach( $obj as $key => $item ) {
if( !is_nan( intval( $key ) ) && is_array( $item ) ){
if( in_array( $value, $item ) ) return $item;
} else {
foreach( $item as $child ) {
if(isset($child) && $child == $value) {
return $child;
}
}
}
}
return null;
}
$data = json_decode( $json );
$results = searchJson( $data , 'purpose2' );
print_r( $results );

Related

how to fix XML with <0> tags

i am generating an XML file FROM Json FIle
$array = file_get_contents('Invoice.json');
$json = json_decode($array, true);
$token = $json['invoice'];
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_array($value) ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
$key2 = 'contact_persons'.$key;
}
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$xml_data = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>');
// function call to convert array to xml
array_to_xml($token,$xml_data);
//saving generated xml file;
$result = $xml_data->asXML('Invoice.xml');
inside the XML I have this Error
<contact_persons><0>122396000000033035</0></contact_persons>
and All of my XML data is in one line
how can I Fix This Error and Create the XML to Show in multi-lines?
thank U!
---EDIT--
this is the Json :
{"invoice":{"can_send_in_mail":false,"zcrm_potential_id":"","is_client_review_settings_enabled":false,"discount":0,"taxes":[],"billing_address":{"zip":"","country":"","address":"","city":"","phone":"","attention":"","street2":"","state":"","fax":""},"line_items":[{"bcy_rate":50,"item_total_formatted":"\u20ac50,00","salesorder_item_id":"","line_item_id":"122396000000033067","rate_formatted":"\u20ac50,00","header_id":"","documents":[],"item_type":"","item_type_formatted":"","purchase_rate":"","description":"asdfasdfasdf","discount":0,"item_order":0,"project_id":"","rate":50,"markup_amount":0,"pricebook_id":"","bcy_rate_formatted":"\u20ac50,00","quantity":1,"image_document_id":"","item_id":"","expense_receipt_name":"","tax_name":"INPS","item_total":50,"header_name":"","item_custom_fields":[],"tax_id":"122396000000032221","purchase_rate_formatted":"","unit":"","tax_type":"tax","time_entry_ids":[],"name":"","tax_percentage":4,"markup_amount_formatted":"\u20ac0,00","expense_id":""},{"bcy_rate":200,"item_total_formatted":"\u20ac200,00","salesorder_item_id":"","line_item_id":"122396000000033441","rate_formatted":"\u20ac200,00","header_id":"","documents":[],"item_type":"","item_type_formatted":"","purchase_rate":"","description":"3334 asdf","discount":0,"item_order":1,"project_id":"","rate":200,"markup_amount":0,"pricebook_id":"","bcy_rate_formatted":"\u20ac200,00","quantity":1,"image_document_id":"","item_id":"","expense_receipt_name":"","tax_name":"INPS","item_total":200,"header_name":"","item_custom_fields":[],"tax_id":"122396000000032221","purchase_rate_formatted":"","unit":"","tax_type":"tax","time_entry_ids":[],"name":"","tax_percentage":4,"markup_amount_formatted":"\u20ac0,00","expense_id":""}],"payment_expected_date_formatted":"","balance":267,"terms":"asdf fgsdfg sdfg ","credits_applied":0,"credits_applied_formatted":"\u20ac0,00","invoice_number":"INV-000001","payment_options":{"payment_gateways":[]},"stop_reminder_until_payment_expected_date":false,"customer_default_billing_address":{"zip":"","country":"","address":"","city":"","phone":"","street2":"","state":"","fax":"","state_code":""},"sub_total_inclusive_of_tax":0,"inprocess_transaction_present":false,"exchange_rate":1,"approver_id":"","estimate_id":"","submitted_date_formatted":"","sales_channel":"direct_sales","merchant_name":"","shipping_charge_formatted":"\u20ac3,00","status_formatted":"Draft","reference_number":"ככגעכ","shipping_charge_tax_id":"","ecomm_operator_name":"","is_autobill_enabled":false,"discount_percent":0,"shipping_charge_tax_name":"","page_height":"11.69in","status":"draft","reader_offline_payment_initiated":false,"schedule_time_formatted":"","discount_total":0,"tax_total":0,"is_viewed_by_client":false,"adjustment_formatted":"\u20ac4,00","balance_formatted":"\u20ac267,00","write_off_amount":0,"salesorder_id":"","currency_code":"EUR","page_width":"8.27in","sub_statuses":[],"bcy_total":267,"last_reminder_sent_date_formatted":"","date_formatted":"14/06/2020","client_viewed_time_formatted":"","salesorders":[],"adjustment_description":"Adjustment","last_modified_time":"2020-06-14T21:15:18+0200","currency_symbol":"\u20ac","ach_supported":false,"shipping_bills":[],"discount_type":"entity_level","transaction_rounding_type":"no_rounding","contact_persons_details":[],"roundoff_value":0,"template_name":"","schedule_time":"","deliverychallans":[],"salesorder_number":"","template_id":"122396000000000103","customer_name":"Thest Compan","customer_id":"122396000000033033","roundoff_value_formatted":"\u20ac0,00","unused_retainer_payments_formatted":"\u20ac0,00","total_formatted":"\u20ac267,00","discount_total_formatted":"\u20ac0,00","payment_terms_label":"Due on Receipt","show_no_of_copies":true,"date":"2020-06-14","submitted_date":"","notes":"Thanks for your business.","template_type_formatted":"","late_fee":{"amount":0,"rate_formatted":"\u20ac0,00","rate":0,"name":"","amount_formatted":"\u20ac0,00","frequency_type":"month","type":"percentage"},"documents":[],"client_viewed_time":"","discount_amount":0,"ecomm_operator_id":"","shipping_charge_inclusive_of_tax":3,"last_modified_by_id":"122396000000032001","write_off_amount_formatted":"\u20ac0,00","payment_discount_formatted":"\u20ac0,00","invoice_id":"122396000000033059","contact_category":"","template_type":"","recurring_invoice_id":"","color_code":"","contact_persons":["122396000000033035"],"can_send_invoice_sms":true,"shipping_charge_tax":"","bcy_tax_total":10,"created_time":"2020-06-14T18:33:43+0200","created_date_formatted":"14/06/2020","last_payment_date_formatted":"","is_inclusive_tax":false,"custom_fields":[],"last_payment_date":"","discount_applied_on_amount_formatted":"\u20ac0,00","price_precision":2,"sub_total_inclusive_of_tax_formatted":"\u20ac0,00","current_sub_status_formatted":"Draft","payment_discount":0,"approvers_list":[],"shipping_charge_tax_percentage":"","zcrm_potential_name":"","adjustment":4,"created_by_id":"122396000000032001","is_backorder":"","current_sub_status":"draft","discount_amount_formatted":"\u20ac0,00","due_date_formatted":"14/06/2020","is_discount_before_tax":true,"shipping_charge_inclusive_of_tax_formatted":"\u20ac3,00","attachment_name":"","ach_payment_initiated":false,"last_reminder_sent_date":"","merchant_id":"","payment_terms":0,"shipping_charge_exclusive_of_tax":3,"total":267,"shipping_charge_exclusive_of_tax_formatted":"\u20ac3,00","tax_total_formatted":"\u20ac0,00","current_sub_status_id":"","sub_total_formatted":"\u20ac250,00","tax_amount_withheld":0,"tax_amount_withheld_formatted":"\u20ac0,00","custom_field_hash":{},"bcy_shipping_charge":3,"shipping_address":{"zip":"","country":"","address":"","city":"","phone":"","attention":"","street2":"","state":"","fax":""},"next_reminder_date_formatted":"","shipping_charge_tax_formatted":"","bcy_discount_total":0,"shipping_charge_tax_type":"","orientation":"portrait","discount_applied_on_amount":0,"due_date":"2020-06-14","no_of_copies":1,"submitter_id":"","submitted_by":"","subject_content":"This is The Subject","payment_made_formatted":"\u20ac0,00","payment_expected_date":"","unused_retainer_payments":0,"bcy_sub_total":250,"is_emailed":false,"reminders_sent":0,"salesperson_name":"","salesperson_id":"","shipping_charge":3,"payment_made":0,"bcy_adjustment":4,"sub_total":250,"allow_partial_payments":false,"created_date":"2020-06-14","currency_id":"122396000000000071","invoice_url":"https://zohosecurepay.eu/invoice/otwsrl/secure?CInvoiceID=2-6ca32e7b078791fcdcc5ead77dbc52a7b54cc4d3c1c1bb6d49d351c9232255b05582a0db903a6955a054be84c7c26eeb73482b971d9cd4781af23344c636f0a15ff36ce7c9675220 ","payment_reminder_enabled":true}}
The problem comes from when you have something which isn't an array which has a key of 0. So what I've done here is to move the check for a numeric key outside the if and so it gets applied to either time you add the key into the structure...
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}

simpleXmlIterator->valid() returns false for valid xml

I am trying to use the simpleXmlIterator to iterate through the following xml. Which xmlspy and notepad++ claim are valid. The simplexmlelement->asXML() returns the same input. However simpleXmlIterator->valid() returns false even after simpleXmlIterator->rewind().
Why does the function simpleXmlIterator->valid() consider it invalid?
My php code which echos N
$xml = new simpleXmlIterator( $xmlstring );
$xml->rewind();
echo $xml->valid() ? "Y" : "N";
XML used in $xmlstring
<tns1:transaction xmlns:tns="http://www.cancerresearchuk.org/di/r17/commonTypes" xmlns:tns1="http://www.cancerresearchuk.org/di/r17/supplier/newdonate" xsi:schemaLocation="http://www.cancerresearchuk.org/di/r17/commonTypes commonTypesDI.xsd http://www.cancerresearchuk.org/di/r17/supplier/newdonate supplier_newdonate_Version4.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tns1:reference>DG007</tns1:reference>
<tns1:supporter>
<tns1:primaryExternalReferenceId>DeepsSceThree</tns1:primaryExternalReferenceId>
<tns1:primaryDataSourceCode>ND</tns1:primaryDataSourceCode>
<tns1:secondaryExternalReferenceId></tns1:secondaryExternalReferenceId>
<tns1:secondaryDataSourceCode></tns1:secondaryDataSourceCode>
<tns1:forename>TT</tns1:forename>
<tns1:startDate>2014-07-15T13:11:20.000000000</tns1:startDate>
<tns1:source>12XSU7006</tns1:source>
<tns1:statusCode>Live</tns1:statusCode>
<tns1:statusDate>2014-07-29</tns1:statusDate>
<tns1:surname>GuptaSceThree</tns1:surname>
<tns1:title>Sir</tns1:title>
<tns1:address>
<tns1:addressLine1>28 Cadmus Court</tns1:addressLine1>
<tns1:addressLine2></tns1:addressLine2>
<tns1:addressLine3></tns1:addressLine3>
<tns1:city>London</tns1:city>
<tns1:country>United Kingdom</tns1:country>
<tns1:county>Cheshire</tns1:county>
<tns1:postalCode>OX4 2WB</tns1:postalCode>
<tns1:startDate>2014-01-13</tns1:startDate>
<tns1:validationStatus>NV</tns1:validationStatus>
</tns1:address>
<tns1:contactInfo-Phone>
<tns1:phoneNumber>01231231221</tns1:phoneNumber>
</tns1:contactInfo-Phone>
<tns1:contactInfo-Email>
<tns1:emailAddress>james#johnson.com</tns1:emailAddress>
</tns1:contactInfo-Email>
<tns1:contactInfo-Mobile>
<tns1:mobileNumber>07516655678</tns1:mobileNumber>
</tns1:contactInfo-Mobile>
<tns1:directDebit>
<tns1:accountName>JessiAccName</tns1:accountName>
<tns1:amount>20.12</tns1:amount>
<tns1:bankAccountNumber>43608868</tns1:bankAccountNumber>
<tns1:bankSortCode>050370</tns1:bankSortCode>
<tns1:bankAccountCode-CRUK>121</tns1:bankAccountCode-CRUK>
<tns1:frequency>Monthly</tns1:frequency>
<tns1:product>CRDD</tns1:product>
<tns1:reference>Deeps3</tns1:reference>
<tns1:source>Donations</tns1:source>
<tns1:paymentDay>19</tns1:paymentDay>
<tns1:toBeGiftAided>Y</tns1:toBeGiftAided>
<tns1:letterCodeGAD>09DTDVGC</tns1:letterCodeGAD>
<tns1:methodGAD>Written</tns1:methodGAD>
<tns1:inMemoryName>TOM</tns1:inMemoryName>
<tns1:motivation>MEM</tns1:motivation>
<tns1:dataSource>ND</tns1:dataSource>
</tns1:directDebit>
<tns1:listOfSuppressionsPreferences>
<tns1:suppressionsPreferences>
<tns1:startDate>2014-08-18</tns1:startDate>
<tns1:suppressionPreferenceCode>SMS</tns1:suppressionPreferenceCode>
<tns1:source>12XSU7009</tns1:source>
</tns1:suppressionsPreferences>
</tns1:listOfSuppressionsPreferences>
<tns1:listOfMailingActivities>
<tns1:mailingActivities>
<tns1:originatorActivityID>SK-ACT-OID0048</tns1:originatorActivityID>
<tns1:category>Donate in Memory</tns1:category>
<tns1:endDate>2014-08-20T21:21:01.000000000</tns1:endDate>
<tns1:letterCode>1VGA</tns1:letterCode>
</tns1:mailingActivities>
</tns1:listOfMailingActivities>
</tns1:supporter>
</tns1:transaction>
The reason behind this is that I want to convert the XML to array/json and the standard solutions are not working because of namesapce. I found this code which claims to work but fails to get through the first hurdle of main while loop, so I assume it is my XML that is the problem. Here is the code I am using
public function xmlToArray( $xml, $namespaces )
{
$a = array();
$xml->rewind();
echo $xml->valid() ? "Y" : "N";
while( $xml->valid() )
{
$key = $xml->key();
if( !isset( $a[$key] ) )
{
$a[$key] = array(); $i=0;
}
else
{
$i = count( $a[$key] );
}
$simple = true;
foreach( $xml->current()->attributes() as $k=>$v )
{
$a[$key][$i][$k]=(string)$v;
$simple = false;
}
if( $this->namespaces )
{
foreach( $this->namespaces as $nid=>$name )
{
foreach( $xml->current()->attributes( $name ) as $k=>$v )
{
$a[$key][$i][$nid.':'.$k] =( string )$v;
$simple = false;
}
}
}
if( $xml->hasChildren() )
{
if( $simple ) $a[$key][$i] = $this->xmlToArray( $xml->current(), $this->namespaces );
else $a[$key][$i]['content'] = $this->xmlToArray( $xml->current(), $this->namespaces);
}
else
{
if($simple)
{
$a[$key][$i] = strval( $xml->current() );
}
else
{
$a[$key][$i]['content'] = strval( $xml->current() );
}
}
$i++;
$xml->next();
}
return $a;
}

create multidimensional array from json object list

I have a json feed that is more or less a list of objects
each has it's own id and idParent. objects that have idParent of null are the base parent elements. What I'm trying to achieve is to make a proper multidimensional array like a tree view. Keep in mind that children can have children too.
{
"obj1":{
"idParent":null,
"id":"parent1"
},
"obj2":{
"idParent":null,
"id":"parent2"
},
"obj3":{
"idParent":null,
"id":"parent3"
},
"obj4":{
"idParent":null,
"id":"parent4"
},
"obj5":{
"idParent":null,
"id":"parent5"
},
"obj6":{
"idParent":"parent1",
"id":"layer1-1"
},
"obj7":{
"idParent":"parent1",
"id":"layer1-2"
},
"obj8":{
"idParent":"parent2",
"id":"layer1-3"
},
"obj9":{
"idParent":"parent4",
"id":"layer1-4"
},
"obj10":{
"idParent":"parent3",
"id":"layer1-5"
},
"obj11":{
"idParent":"layer1-1",
"id":"layer2-1"
},
"obj12":{
"idParent":"parent5",
"id":"layer2-2"
},
"obj13":{
"idParent":"layer1-4",
"id":"layer2-3"
},
"obj14":{
"idParent":"layer1-5",
"id":"layer2-4"
},
"obj15":{
"idParent":"layer1-5",
"id":"layer2-5"
}
}
I've managed to filter out the root parents but after that I fail very bad
The first function does filter out the root parent nodes with idParent of null.
function decodeData($data) {
global $out;
foreach ($data as $key => $obj) {
if (is_array($obj)) {
foreach ($obj as $prop => $value) {
if ($prop == 'idParent') {
if($value == null) {
array_push($out, $obj);
unset($data[$key]);
}
}
}
}
}
if (count($data) > 0) {
decodeData($data);
} else {
echo json_encode(array('length'=>count($data)));
}
}
And this is what I'm experimenting on with no result
function decodeData($arrays) {
global $out;
foreach ($arrays as $array_name => $arr) {
foreach ($arr as $arr_prop => $arr_val) {
if ($arr_prop == 'idParent' && $arr_val == null) { // we found root parents
array_push($out, $arr);
unset($arrays[$array_name]); //remove array from the list
} else { // check if idParent is inside out
foreach ($out as $out_arr_name => $out_arr) { // iterate through out arrays
foreach ($out_arr as $out_arr_prop => $out_prop_val) { //
if ($out_arr_prop == 'id' && $arr_prop == 'idParent' && $out_arr_val == $arr_val) {
array_push($out_arr['children'], $obj);
unset($arrays[$array_name]);
}
}
}
}
}
}
if (count($arrays) > 0) {
decodeData($arrays);
} else {
echo json_encode(array('length'=>count($arrays)));
}
}
If anyone could provide some help I would really appreciate it.
I couldn't figure out what output do you want, so I just made a simple tree structure:
$data = json_decode( $your_json_string );
// Store each element in a lookup table indexed by element id
// 0th pass: put a fake root element there
$by_id = array(
'*' => new stdclass
);
// First pass: put each element into there
foreach( $data as $o ) $by_id[ $o->id ] = $o;
// Second pass: add each element into its parent's children array
foreach( $data as $o ){
$pid = $o->idParent ? $o->idParent : '*';
$p = $by_id[ $pid ];
$p->children[] = $o;
}
// Trash everything else, we start from the (fake) root element:
$tree = $by_id['*']->children;
/**** REVERSE ****/
$todo = $tree;
$json = array();
while( $todo ){
$o = array_shift( $todo );
if( isset( $o->children )){
$todo = array_merge( $todo, $o->children );
unset( $o->children );
}
$json[] = $o;
};
echo json_encode( $json );
The result:
http://codepad.viper-7.com/V7PjDh

php foreach loop not working correctly

public function include_header( $h, $h_data ) {
// Require header file
if (isset($h) && !empty($h)) {
$this->header_file = 'includes/header/'.$h;
} else { return false; }
// Pass optional array of parameters
if (isset($h_data) && is_array($h_data) && !empty($h_data)) {
// Loop through array & assign keys to appropriate class members
foreach($h_data as $key => $val) {
if ($key == 'doctype') { $this->doctype = $val; }
if ($key == 'title') { $this->title = $val; }
if ($key == 'meta') {
// The meta key is should be an array in h_data
// so, we'll have to loop through the meta array
// in order to parse the individual meta elements.
foreach($key as $meta_key => $meta_val) {
$this->error = $meta_key;
}
}
}
} else { return false; }
}
I'm trying to loop through a multidimensional array, where I have the following variable...
$h_data['meta']['individual_element']
I'm trying to loop through the 'meta', so I can access each individual value, but I'm having trouble. Please help! Thanks in advance!
foreach($key as $meta_key => $meta_val) {
$this->error = $meta_key;
}
... should be
foreach($val as $meta_key => $meta_val) {
$this->error = $meta_key;
}
if ($key == 'meta') {
// The meta key is should be an array in h_data
// so, we'll have to loop through the meta array
// in order to parse the individual meta elements.
foreach($val as $meta_key => $meta_val) { //val not key
$this->error = $meta_key;
}

only need to delete one product from my cart, not all products with same ID

I don't understand why this code won't only delete the pizza_id with the given key that is passed through the URL. I echo back the $_GET['key'] value to check if I have the desired number and it works fine.
The key value comes from another foreach $key=>$value loop that builds the shopping cart and has a delete link with the pizza id and the $key in it.
switch ($action) {
case 'add':
if ($cart) {
$cart .= ','.$_GET['pizza_id'];
} else {
$cart = $_GET['pizza_id'];
}
break;
case 'delete':
echo "KEY: ".$_GET['key']."<br>";
if ($cart) {
$items = explode(',',$cart);
$newcart = '';
foreach ($items as $key => $item)
{
if ($_GET['pizza_id'] != $item && $GET['key']!= $key )
{
if ($newcart != '')
{
$newcart .= ','.$item;
}
else
{
$newcart = $item;
}
}
}
$cart = $newcart;
}
break;
}
EDIT: maybe I should also mention the basis of the code comes from this webpage http://v3.thewatchmakerproject.com/journal/276/
Well, at a minimum, you don't need the $key in the foreach.
if ($cart) {
// you car is now an array of $items.
$items = explode(',',$cart);
$key = $_GET[ 'key' ];
// are you sure pizza_id is correct too? You may want to echo/log it
// if there is an $item which corresponds to $key, remove it.
if( isset( $items[ $key ] ) )
unset( $items[ $key ] );
// this loop searches for all indexes of $_GET[ 'pizza_id' ] and removes them
// comment this out if you don't want to do that. For some reason
// I missed it the first go round.
while( ($pos = $array_search( $items, $_GET[ 'pizza_id' ] ) !== FALSE )
{
array_splice( $items, $pos, 1 );
}
// implode afterwards
$cart = implode( ',', $items );
}
Another poster pointed out that your original code also has $GET['key']. Badness 10000. Do you have your warnings and error output set at the maximum level during development?
Check if this will work
foreach ($items as $key => $item)
{
if ($_GET['pizza_id'] != $item && $GET['key']!= $item )
I don't get your problem ... but you have a typo in the if-condition.
$GET[
lacks the underscore ...

Categories