Looking to take the data from two API endpoints and merge them into one array using PHP.
While I'm aware of functions like array_merge, not actually looking to append the data, more like map it together at the end. Below is an example of what I'm looking to achieve.;
$api1_endpoint = esc_url_raw( "http://api.com/endpoint" );
$api2_endpoint = esc_url_raw( "http://api.com/endpoint2" );
$api1 = json_decode( $api1_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["productColor"]=> string(3) "red" }
$api2 = json_decode( $api2_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["quantityAvailable"]=> float(5) }
$combined_apis = // function to combine $api1 and $api2 by ["sku"] or other key
foreach($combined_apis as $combined){
echo $combined->sku;
echo $combined->quantityAvailable;
}
Here is the function for that
public function combine_api_result($api1, $api2) {
$output = $api1;
foreach($api2 as $key => $value) {
if ( ! isset($output[$key])) {
$output[$key] = $value;
}
}
return $output;
}
Related
I am using a working function that perfectly displays the contents of a csv file.
function csv2array( $filename, $delimiter )
{
// read the CSV lines into a numerically indexed array
$all_lines = #file($filename);
if( !$all_lines )
{
return FALSE;
}
$csv = array_map( function( &$line ) use ( $delimiter )
{
return str_getcsv( $line, $delimiter );
}, $all_lines );
// use the first row's values as keys for all other rows
array_walk( $csv, function( &$a ) use ( $csv )
{
$a = array_combine( $csv[0], $a );
});
array_shift( $csv ); // remove column header row
return $csv;
}
$items = csv2array( 'filetest.csv', ';' );
//print_r( $items );
echo '<pre>';
var_dump( $items );
echo '</pre>';
The var_dump output is perfect and displays:
array(40) {
[0]=>
array(4) {
["Jurisdiction"]=>
string(2) "AL"
[" Total Distance(mi.)"]=>
string(7) "1730.68"
[" Off Road(mi.)"]=>
string(4) "2.63"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[1]=>
array(4) {
["Jurisdiction"]=>
string(2) "AR"
[" Total Distance(mi.)"]=>
string(6) "826.27"
[" Off Road(mi.)"]=>
string(4) "1.35"
[" Toll Road(mi.)"]=>
string(1) "0"
}
[2]=>
array(4) {
["Jurisdiction"]=>
string(2) "DE"
[" Total Distance(mi.)"]=>
string(5) "49.11"
[" Off Road(mi.)"]=>
string(4) "0.34"
[" Toll Road(mi.)"]=>
string(4) "6.57"
}
I am trying to display the values of those $rows which sounds super easy but I am getting empty values and searched the internet and cannot find the right way to do it. Here is my code:
foreach($items as $row)
{
echo $row[0]. " ".$row[1]." ".$row[2]."TESTTEST<br>";
}
but I only get the TESTTEST results but the total number of times it displays TESTTEST is correct but the values are empty so what am I missing? I searched this site and others and they seem easy but mine isn't working. Thanks.
What you could do is nest the loop or implode it.
Nesting:
foreach($items as $row)
{
foreach($row as $val){
echo $val . " ";
}
echo "TESTTEST<br>";
}
Or implode:
foreach($items as $row)
{
echo implode(" ", $row);
echo "TESTTEST<br>";
}
You shouldn't use a numerical index for the data as you've just added the column name as the index.
But you can just implode() the data anyway...
foreach($items as $row)
{
echo implode(" ", $row)."TESTTEST<br>";
}
Thanks for the help everyone I got it the way I want and can expand from here on out. I was looking for this code:
$i = 0;
foreach($items as $row)
{
echo $row['Jurisdiction'] . $row[' Total Distance(mi.)'] . "TESTTEST<br>";
$i++;
}
echo 'total: ' . $i;
I will be sure to trim out the space on the names.
I get translations from database and want to get generate it in Javascript object, like:
var Lang = {
eng: {
txtUserName: 'Username',
txtLogout: 'Logout'
},
dnk: {
txtUserName: 'Brugernavn',
txtLogout: 'Afslut'
}
}
I got stuck in loops, the result I get is not what I need.
This is my PHP:
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' ) :
for ( $i = 1; $i <= 1; $i++ ){
var_dump($translationsall[$i]);
}
endif;
endforeach;
echo '},';
echo "\r\n";
endforeach;
?>
}
And this is what I get:
var Lang = {
dnk: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
},
eng: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
}
How can I edit my loops to get result I need?
Maybe there is a smarter way to generate Lang object?
And, forgot to mention that I need only few translations, that's why I have this in PHP if:
if ( $translation['it_text'] == 'txtUserName' ) :
//stuff
endif;
Any ideas are welcome :)
And this what I get from var_dump($translationsall):
array(2748) {
[0]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[1]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[2]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Afslut"
}
[3]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Logout"
}
[4]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(9) "Hent Igen"
}
[5]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(7) "Refresh"
}
}
Please, don't do this. - Make an API call to a PHP backend producing the data you need. - Using either out of the box functions such as $.ajax from jQuery or other prebuilt frameworks will help you achieve this.
If you still want to go down the line of dynamically doing this (your question) - remove var_dump - which is ultimately dumping the type and other details (as it should) and use foreach (key, value) which will help you generate what you need. - But rather going down this dodgy route I'd recommend you take a look at how to serve an API using Laravel or other frameworks.
You could pass data from PHP to JS with JSON.
From PHP, you can use json_encode():
echo json_encode($translation);
And in your JS use JSON.parse():
var obj = JSON.parse('{"key":value}');
You can then do:
<?php
$allLangs = $this->params->getLanguages;
$json = json_encode($allLangs);
?>
<script>
var Lang = JSON.parse('<?php echo $json; ?>');
</script>
As others here have already mentioned; it is a bad idea to dynamically create your javascript like this - I would instead use JSON to serialize and deserialize the data. Anyway, if you insist on dynamic creation; it'll probably be something along the lines of;
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) {
echo $allLang->lang_code . ': {';
foreach ( $translationsall as $translation ) {
$total_words_to_translate = count($translation);
for($i = 0; i <= $total_words_to_translate; $i++){
if ( $translation['it_text'] == 'txtUserName' ){
print("txtUserName: ".$translationsall[$i]);
}
if ( $translation['it_text'] == 'txtLogout' ){
print("txtLogout: ".$translationsall[$i]);
}
}
}
echo '},';
echo "\r\n";
}
?> }
Its somewhat hard to determine the exact code when we don't know the structure / naming conventions of your database / variables.
Use json_encode:
var Lang = <?php
$all_langs = $this->params->getLanguages();
echo json_encode($all_langs);
?>;
Not sure how close I am with the data definitions, but I've included them so you can see what I'm assuming and hopefully be able to adjust it to your needs.
The way it works is that it starts at the beginning of $translationsall array and assumes that the $allLangs array is in the same order as the entries ( so in this case the dnk and then the eng values). These it then populates into the output under the language key, with it_text as the key and it_name as the translation.
$translationsall = [["it_text" => "txtLogout", "it_name"=>"Afslut"],
["it_text"=> "txtLogout", "it_name"=> "Logout"],
["it_text" => "txtLogout2", "it_name"=>"Afslut2"],
["it_text"=> "txtLogout2", "it_name"=> "Logout2"]
];
$allLangs = [ (object)["lang_code"=> "dnk"], (object)["lang_code"=> "eng"] ];
$countTrans = count($translationsall);
$out = [];
$i = 0;
while( $i < $countTrans ) {
foreach ( $allLangs as $language ) {
$out[$language->lang_code][$translationsall[$i]["it_text"]] = $translationsall[$i]["it_name"];
$i++;
}
}
echo json_encode($out, JSON_PRETTY_PRINT);
This prints out
{
"dnk": {
"txtLogout": "Afslut",
"txtLogout2": "Afslut2"
},
"eng": {
"txtLogout": "Logout",
"txtLogout2": "Logout2"
}
}
You can try with echo see bellow code :
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' and $translation['itl_lang_code '] == $allLang->lang_code) :
echo "txtUserName:'".$translation['it_text']."',txtLogout:'".$translation['it_name']."' ";
endif;
endforeach;
echo '}';
echo '},';
echo "\r\n";
endforeach;
?>
}
Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}
I am trying to retrieve data from this array in php.
array(2) {
["getWysiwyg"]=>
string(37) "[{"basicsDescription":"<p><br></p>"}]"
["getGoal"]=>
string(27) "[{"iconURL":"","title":""}]"
}
I tried Input::get('getWysiwyg') it returns [{"basicsDescription":"<p><br></p>"}]
Now how could i get the value i.e <p><br></p>
As I see your array items are json encoded ..
Try to decode them as this:
foreach($array as $key=>$value){
$decodedValue = json_decode($value, true);
print_r($decodedValue);
}
You have to use json_decode(), because the string [{"basicsDescription":"<p><br></p>"}]represents an array with an object in JSON.
$string = '[{"basicsDescription":"<p><br></p>"}]';
$objectArray = json_decode( $string );
$objectArray now looks like:
array(1) {
[0]=>
object(stdClass)#1 (1) {
["basicsDescription"]=>
string(11) "<p><br></p>"
}
}
To get the value of basicsDescription you need to access the array in this case with the index 0, then you have the object:
$object = $objectArray[0];
Once you've got the object you can access it's attributes with the object operator ->:
$object->basicsDescription;// content: <p><br></p>
Short form of this:
$string = '[{"basicsDescription":"<p><br></p>"}]';// in your case Input::get('getWysiwyg')
$objectArray = json_decode( $string );
$objectArray[0]->basicsDescription;
If it's possible, that there are more than one item in it, you should go for foreach
If all items of your array representing JSON strings you can use array_map():
$array = array(
"getWysiwyg" => '[{"basicsDescription":"<p><br></p>"}]',
"getGoal" => '[{"iconURL":"","title":""}]'
);
$array = array_map( 'json_decode' , $array );
echo "<pre>";
var_dump( $array );
This will output:
array(2) {
["getWysiwyg"]=>
array(1) {
[0]=>
object(stdClass)#1 (1) {
["basicsDescription"]=>
string(11) "<p><br></p>"
}
}
["getGoal"]=>
array(1) {
[0]=>
object(stdClass)#2 (2) {
["iconURL"]=>
string(0) ""
["title"]=>
string(0) ""
}
}
}
Decode and print as follows
$object = json_decode(Input::get('getWysiwyg'));
print $object[0]->basicsDescription;
or directly with the help of array dereferencing
print json_decode(Input::get('getWysiwyg'))[0]->basicsDescription;
will output
<p><br></p>
I've been trying for hours now to get the title field from the json code. Below is my php code
$search = $_GET['search'];
$new = str_replace(' ', '+', $search);
$url = "http://api.themoviedb.org/3/search/movie?api_key=###&query=".$new;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$title = $json_data->title;
echo $title;
this is the var dump of the json
array(4) { ["page"]=> int(1) ["results"]=> array(1) { [0]=> array(10) { ["adult"]=> bool(false) ["backdrop_path"]=> string(32) "/4uJZvmEMX6Z6ag3bzym5exLY9wI.jpg" ["id"]=> int(65) ["original_title"]=> string(6) "8 Mile" ["release_date"]=> string(10) "2002-11-08" ["poster_path"]=> string(32) "/dXzTrKwpbLpCqn8O70FUUhNbYQT.jpg" ["popularity"]=> float(3.792332418578) ["title"]=> string(6) "8 Mile" ["vote_average"]=> float(6.2) ["vote_count"]=> int(185) } } ["total_pages"]=> int(1) ["total_results"]=> int(1) }
the error i keep getting is Notice: Trying to get property of non-object
any help would be greatly appreciated.
$json_data = json_decode($json, true);
will return an array not object
so you need to use as
$json_data["title"];
NOTE : Your json decoded array is nested so you may need to use as in your case.
$json_data["results"][0]["title"];
Or better loop through and get the desired data.
I just started using PHP and I THINK this might help you... but i'n not sure
foreach($json_data as $key => $value){
if($key == "results"){
$json_data2 = $value;
}
}
foreach($json_data2 as $key => $value){
if($key == "original_title"){
$title = $value;
}
}
echo $title;