PHP - Optional JSON field - php

I would like to output a JSON string with an optional fields.
Right now I do it as simple as:
echo json_encode(array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
));
Now, say, I would like to include/exclude the 'asd' element based on some logic (using an inline if or some function or something else).
I have no idea how to do it, because, AFAIK, there is no such type in PHP that can force json_encode to skip this field - everything returns null or empty fields but does not skip the field itself.
Any ideas someone?

do you mean something like this:
$arr = array(
array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
),
array(
'qwe' => 4,
'asd' => '',
'zxc' => 6
)
);
foreach ($arr as $key => $row) {
if ($row['asd'] == '') {
unset($arr[$key]['asd']);
}
}
echo json_encode($arr);

Related

Is there a way to get a named key/value from SUBARRAY without knowing the main key?

Short: Is there a way to get a named key/value from SUBARRAY without knowing the main key ?
Long:
Ive got a foreach loop that extracts text-files & turns them into individual / single arrays (resetting the array between each file)...
example:
Array
(
[Blah Blah] => Array
(
[number] => 10
[name] => nameBlah
[image] =>
)
)
Array
(
[pinkblue597] => Array
(
[number] => 18
[name] => nameBlah68
[image] =>
)
)
(the 1st part to turn into array is used by multiple parts of a process so I dont want to add unnecessary code)
I want to extract the value of "name" and "number", however I do not know the value / format of the key in advance.. - Example: pinkblue597
If I do print_r, I do see the array as I want...
print_r($found,true)."\n";
but if I do this, $name=$found[0]; I get no results for "$name"...
or
if I do this, $name=$found[0]["name"]; I get no results for "$name"...
I could do this via a foreach loop, but it seems inefficient...
PS there will only be ONE (unknown) key in this array, & a sub-array. The sub array is always the same.
Edited: made the code easier to see (forgot to do this)
If the array formation is going to be the same all the time...
then a (nested) foreach loop will suffice, take the example below,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'another name',
'number' => 24
]
];
foreach ($a as $key => $subArray) {
foreach ($subArray as $subKey => $value) {
echo $subArray[$subKey] . '<br>';
}
}
?>
Output
name
15
another name
24
Or...
You could use array_values,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'name',
'number' => 24
]
];
$a = array_values($a);
echo $a[0]['name'];
?>
Which would turn the first associative array in to numeric indexes and would like so,
array(
0 => array(
'name' => 'first name',
'number' => 15,
),
1 => array(
'name' => 'name',
'number' => 24,
)
)
I'm not sure why you're creating a nested array in the first place if you only intend to discard it immediately, but since the array only appears to have a single element, and you only care about that element, you can simple use array_pop
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
];
$data = array_pop($a);
echo $data['name']; // gives you 'first name'
Note that array_pop is destructive. So if you don't want this behavior you could use something like end instead.
$data = end($a); // same effect as array_pop but non-destructive
echo $data['name']; // also gives you 'first name'
With that said, the foreach construct isn't necessarily inefficient. I believe your true concern is around finding a simpler way to dereference the nested array. The easiest way to do that in your case is going to be using something like end($a)['name'] which gives you the kind of straight-forward dereferencing you're looking for.
You can use array_map() to achieve this...
array_map — Applies the callback to the elements of the given arrays. This will loop all the array elements through callback function and you can print each element present in the sub array..
<?php
$myArry = array(
'Blah Blah' => array(
'number' => 10,
'name' => 'Blah Blah 1',
),
'pinkblue597' => array(
'number' => 15,
'name' => 'Blah Blah 2',
)
);
array_map(function($arr){
echo 'Name : '.$arr['name'].'<br>';
echo 'Number : '.$arr['number'].'<br>';
},$myArry);
?>
This will give you :
Name : Blah Blah 1
Number : 10
Name : Blah Blah 2
Number : 15

Search for key and value in php arrays

So I have two array, the first one is like:
$MyArray = [
['id' => 1, number => 32],
['id' => 2, number => 4]
];
and the other is like:
$OtherArray = [
['id' => 1, 'show' => X],
['id' => 5, 'show' => X]
];
Where is X, I want it to be equal with the 'number' value of $MyArray where key 'id' = its id.
If there is no $MyArray.id which is equal to $OtherArray.id then it should return 0.
I hope you understand what I mean. I tried everything, what I could, yet, with no success.
Have you tried using a foreach loop here?
Here is a quick example... PHPaste Snippet
<?php
$firstArray = array(
array(
"id" => 1,
"something" => "Hello, World!"
),
array(
"id" => 3, // 3 on purpose
"something" => "Hello, mom?"
)
);
$secondArray = array(
array(
"id" => 1,
"thing" => null
),
array(
"id" => 2,
"thing" => null
)
);
foreach ($firstArray as $key => $value) {
foreach ($secondArray as $k => $v) {
if ($value['id'] == $v['id']) {
echo "Found one!\n------\n" . print_r($value, true) . "\ncontains the same ID as\n\n" . print_r($v, true) . "\n------\n";
// you may also do this if you want
// $secondArray[$k]['thing'] = $value['id'];
// this would set "thing" (in the second array) to the value of "id" (in the first array)
}
}
}
EDIT Here is a second example, displaying how you could use it as a function... PHPaste Snippet.
Note: I used the OLD array syntax because it's easier for new programmers to understand.
So, essentially what you are doing is iterating through each item in $firstArray, comparing it to each item in $secondArray, by doing a nested foreach within side the first foreach if that makes sense...?
Here is what I just said in simple form:
go through each item in array 1
--> compare it to each item in array 2
You may also notice my use of PHP's lovely function, print_r(). This displays objects and arrays in a slightly, clearer, form.
You can also see that I am getting the values from within the arrays by using $value['id'] and $v['id']. These were defined in my foreach declaration, foreach ($firstArray as $key => $value); $value is an associative array, so you can simply get a value by key just as you would if you created an array like this:
$myArray = [
"id" => 1
];
and grabbed values like this:
echo $myArray['id']; // 1
Hopefully this helped.

Creating array from translated datas and merging an array in PHP

I'm designing a site with multi-language support. Our main language is Turkish. I do not want while admin is inserting Turkish data, empty other fields in foreign languages. So when the Turkish data insert in ends with "_tr" columns, in the foreign language fields ends with "_en" and "_de", I want to get from Yandex Translator data which is automatically translated.
Here is my table structure:
My data structure like this which will be inserted:
$data = array(... 'parent_id' => 234, 'date' => "2014-08-31 23:07:47", 'status' => 1);
I want to to add in "..." like this:
$translated = array('fruit_tr' => "Elma", 'fruit_en' => "Apple", 'fruit_de' => "Apfel", 'color_tr' => "Kırmızı", 'color_en' => "Red", 'color_de' => "Rot");
I tried this:
$from_turkish = array('fruit' => "Elma", 'color' => "Kırmızı");
public function Translate ($from_turkish) {
$langs = array("tr", "en", "de");
$translated = array();
foreach ($langs as $lang){
foreach ($from_turkish as $field_name => $value) {
$translated[] = array($field_name.'_'.$lang => YandexTrApi($value, 'tr', $lang));
}
}
return $translated;
}
YandexTrApi function returns translated data. Finally, I used array_merge function like this:
$data_array = array_merge($translated, $data);
But it did not take form like this:
$data_array = array('fruit_tr' => "Elma", 'fruit_en' => "Apple", 'fruit_de' => "Apfel", 'color_tr' => "Kırmızı", 'color_en' => "Red", 'color_de' => "Rot", 'parent_id' => 234, 'date' => "2014-08-31 23:07:47", 'status' => 1);
array_merge($translated, $data) is fine and $translated + $data would give the same result in this case, but...
$translated[] = array($field_name.'_'.$lang => YandexTrApi($value, 'tr', $lang));
...this way you'll push new arrays inside $translated array. You need to add new keys only - try this instead:
$translated[$field_name.'_'.$lang] = YandexTrApi($value, 'tr', $lang);
Also the foreach() loops nested like this will give you slightly different order, but I guess you don't need it to match db (as your ... part may be placed before parent_id key).

Using square brackets and assigning variables in PHP

I have seen source code like:
$something = $sql['value']
I have searched a lot about it and I found that it's from arrays. But I didn’t understand the exact meaning.
For example,
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
Can we write code like the following?
if(!empty($people)
$something = $people['a value']
I just need to know how we can declare a variable and give a value in square brackets.
If you are using $something = $people['a value'] it means you are assigning a value of the $people array having an index of a value.
So you don't have that and so it will throw you undefined index error.
You are using a nested associative array and you have to output using something like:
echo $people['Jack']['Age'];
As you wanted a brief example, say you have an array like
$people = array('name'=>'Jack');
Now, when you want to store the name in a variable, you use
$store_name = $people['name'];
echo $store_name; // Echoes "Jack"
Try this:
$people = array(
'Susan' => array('Age' => 24, 'Phone' => '555-123-4567'),
'Jack' => array('Age' => 27, 'Phone' => '555-9876-5432')
);
You can use array and write it like this
$people = array(
'Susan' => array(
'Age' => 24,
'Phone' => '555-123-4567'
),
'Jack' => array(
'Age' => 27,
'Phone' => '555-9876-5432'
)
);
echo $people['Jack']['Age']; // 27
if(!empty($people)
$something = $people['a value']
Square brackets mean index, so $people['a value'] is a value that lays under the 'a value' index of the $people array.
Square brackets are also used as a shortcut for array().. See it here-

Convert a string into array PHP

Sometime back I was getting alot of data via some API and I saved it into a flat file doing a simple var_dump or print_r. Now I am looking to process the data and each line looks like:
" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y',
'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name'
=> 'MNOP', 'email' => 'abc#example.com', 'city' => 'London',
'street_address' => 'Sample', 'first_name' => 'Sparsh',"
Now I need to get this data back into an array format. Is there a way I can do that?
What about first exploding the string with the explode() function, using ', ' as a separator :
$str = "'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',";
$items = explode(', ', $str);
var_dump($items);
Which would get you an array looking like this :
array
0 => string ''middle_initial' => ''' (length=22)
1 => string ''sid' => '1419843'' (length=18)
2 => string ''fixed' => 'Y'' (length=14)
3 => string ''cart_weight' => '0'' (length=20)
...
And, then, iterate over that list, matching for each item each side of the =>, and using the first side of => as the key of your resulting data, and the second as the value :
$result = array();
foreach ($items as $item) {
if (preg_match("/'(.*?)' => '(.*?)'/", $item, $matches)) {
$result[ $matches[1] ] = $matches[2];
}
}
var_dump($result);
Which would get you :
array
'middle_initial' => string '' (length=0)
'sid' => string '1419843' (length=7)
'fixed' => string 'Y' (length=1)
'cart_weight' => string '0' (length=1)
...
But, seriously, you should not store data in such an awful format : print_r() is made to display data, for debugging purposes -- not to store it an re-load it later !
If you want to store data to a text file, use serialize() or json_encode(), which can both be restored using unserialize() or json_decode(), respectively.
Although I wholeheartedly agree with Pascal Martin, if you have this kind of data to deal with, the following (as Pascal's first suggestion mentions) could work depending on your actual content. However, do yourself a favor and store your data in a format that can be reliably put back into a PHP array (serialize, JSON, CSV, etc...).
<pre>
<?php
$str = "\" 'middle_initial' => '', 'sid' => '1419843', 'fixed' => 'Y', 'cart_weight' => '0', 'key' => 'ABCD', 'state' => 'XX', 'last_name' => 'MNOP', 'email' => 'abc#example.com', 'city' => 'London', 'street_address' => 'Sample', 'first_name' => 'Sparsh',\"";
function myStringToArray($str) {
$str = substr($str, 1, strlen(substr($str, 0, strlen($str)-2)));
$str = str_replace("'",'',$str);
$strs = explode(',', $str);
$arr = array();
$c_strs = count($strs);
for ($i = 0; $i < $c_strs; $i++) {
if (strpos($strs[$i],'=>') !== false) {
$_arr = explode('=>',$strs[$i]);
$arr[trim($_arr[0])] = trim($_arr[1]);
}
}
return $arr;
}
print_r(myStringToArray($str));
?>
</pre>
http://jfcoder.com/test/substr.php
Note, you would need to adjust the function if you have comma's within your array member's content (for instance, using Pascal's suggestion about the ', ' token).
It would be better and much easier to work with Serialize and Unserialize instead of var_dump.
in that form, maybe you could try a
explode(' => ', $string)
and then go through the array and put the pairs together in a new array.
As long as it's the output of print_r and an array, you can use my little print_r converter, PHP source code is available with the link.
The tokenizer is based on regular expressions so you can adopt it to your needs. The parser deals with forming the PHP array value.
You will find the latest version linked on my profile page.

Categories