Combined 2 array data - php

I want to do something like bellow using php:
$turl=array(trim($params->get('c2')));
$tname=array(trim($params->get('cn2')));
and want to display each $turl with each $tname.
I tried like this:
$result=array_combine($turl,$tname);
print_r($result);
but given result as:
Array ( [http://184.107.144.218:8282/,http://184.107.144.218:8082/] => ABC Radio,AHH Radio )
But I want like this:
Array ( [http://184.107.144.218:8282/=> ABC Radio,
http://184.107.144.218:8082/=> AHH Radio )
Thanks in advance

maybe you want to use a code similar to this:
$turl = explode(',',trim($params->get('c2')));
$tname = explode(',',trim($params->get('cn2')));
$result=array_combine($turl,$tname);
print_r($result);
The error seems to be into the $turl and $tname arrays creation as array combine should work as intended
Obviously I would add several checks, as, for example, Have the two arrays the same size?
Addendum
In your comment you give me a specimen of what $params->get returns if called with parameters 'c2' and 'cn2'.
$params->get('c2')="hoicoimasti.com,google.com"
$params->get('cn2')="hoicoi,google".
The example code I gave you do what required, or at leas what I was thinking you are trying to obtain. A different code with a different result is:
$turl = explode(',',trim($params->get('c2')));
$tname = explode(',',trim($params->get('cn2')));
$result=array_map(function($x,$y){return $x.','.$y;},$turl,$tname);
print_r($result);
or, if you want to obtains a single string:
$result=join(',',array_map(function($x,$y){return $x.'=>'.$y;},$turl,$tname));
print_r($result);
You can obtain any desired result modifying one of the previous example.
To encase the results in an option you need a slight variation of the array_map user function:
$result=join("\n",array_map(
function($x,$y){
return "<option>$x=>$y</option>";
},
$turl,
$tname
));
print_r($result);
PHP < 5.3 version
Put this function declaration somewhere in the global scope
function formatOption($x,$y){
return "<option>$x=>$y</option>";
};
and then your code will become:
$result=join("\n",array_map( 'formatOption', $turl, $tname));
print_r($result);
If possible I won't clutter the global namespace with function like formatOption,
but when anonymous function are not available
Reference:
array_map
join

Related

pass arguments to a function php

Is it possible to convert an array to a list of elements without using list?
this works well
list($arg_a,$arg_b) = array($foo,$bar);
myfunction($arg_a,$arg_b);
but I'm looking for something similar to that:
$array = array($foo,$bar);
myfunction(php_builtin_function(array($foo,$bar)));
obviusly I can't edit that function!
function myfunction($param_a,$param_b){
...
}
As mentioned in comments, here's what you need:
call_user_func_array('myfunction', php_builtin_function(array($foo,bar)));
Docs
That said, it would be more readable to use list:
$result = php_builtin_function(array($foo,$bar));
list($arg_a, $arg_b) = $result;
myfunction($arg_a, $arg_b);

Access JSON values in PHP

{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

php arrays (and removing certain element)

I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays

PHP: problem inserting array inside an array

I have a script that is using the google charts API and the gChart wrapper.
I have an array that when dumped looks like this:
$values = implode(',', array_values($backup));
var_dump($values);
string(12) "8526,567,833"
I want to use the array like this:
$piChart = new gPieChart();
$piChart->addDataSet(array($values));
I would have thought this would have looked like this:
$piChart->addDataSet(array(8526,567,833));
Howerver when I run the code it creates a chart with only the first value.
Now when I hardcode the values in instead I get each value in the chart.
Does anyone know why it's acting this way?
Jonesy
I think
$piChart->addDataSet(array_values($backup));
// or just: $piChart->addDataSet($backup); depends on $backup
should do it.
$values only contains a string. So if you do array($values), you create an array with one element:
$values = "8526,567,833";
print_r(array($values));
gives
Array
(
[0] => 8526,567,833
)
array(8526,567,833) would be the same as array_values($backup) or maybe even just $backup, that depends on the $backup array.
Looks like you want to use $backup instead of $values as $values is the imploded string... and since 8526,567,833 isn't a valid number, it parses 8526 and leaves the rest alone.

Categories