I have the following data here.
[places] => Array
(
[0] => Drama
[1] => School
[2] => Shounen Ai
[3] => Slice of Life
)
I am trying to store this data into WordPress tags, however it's returning only singular letters.
$i = 0;
foreach($t['places'] as $tag=>$value){
$numbers = $i++;
wp_set_object_terms($post_id , $t['places'][$numbers], "drama_tag",true);
}
This is what it returns, what am I doing wrong?
please edit the image into the post
You're looping over the array in your foreach; you don't need to set up your own increment.
Instead of $t['places'][$numbers], you're simply looking for $value:
foreach($t['places'] as $tag=>$value) {
wp_set_object_terms($post_id, $value, "drama_tag", true);
}
Related
Array
(
[0] => Array
(
[datas] => Array
(
[res] => 1
[rows] => Array
(
[0] => stdClass Object
(
[a] => 11
[b] => 901
[c] => 2
[d] => 2
[e] => A
[f] => BT
[g] => arushi
[h] => arushi#gmail.com
[i] => 123445
[j] => 12355.jpg
)
)
)
)
[1] => Array
(
[datas] => Array
(
[res] => 1
[rows] => stdClass Object
(
[person_name] => arushi
)
)
)
)
if i get the value in that kind off array how can i get the value of
both partially with different variable m not able to understand the
structure of the array..
need to get the value in table seperatly in different different table with same page how i can get the values
You would need to do a foreach loop. The only problem is that if you want to make it dynamic and grab the data by itself without you telling it what to get. If not it means you would have to know exactly what you need and the structure of your results. But seeing that there is a pattern you can do some checks until you reach rows. For example ($array would be the variable that has the data you provided):
foreach ($array AS $arr) {
// To make you function/check work faster,
// before even entering to fetch for data
// you can check if it has any data, else you
// probably will end up with an error
if (isset ($arr ['datas']) && $arr ['datas']) {
foreach ($arr ['datas'] AS $data) {
if (isset ($arr ['res']) && 0 < $arr ['res']) {
// here is where it gets tricky because
// from you example its either an array or an object
// but the kool part about it is that you can convert an object into an array
// or just leave it as is because the foreach will take care of it either way :)
// first check it it is an object and convert if yes
$row = $arr ['rows'];
if (!is_array ($row))
$row = (array)$row; // converting it to array is super easy :)
foreach ($row AS $key=>$dat) {
// from here your result can either be another array or just data
// so you run the check once more
if (is_array ($dat)) {
foreach ($dat AS $k=>$d) {
echo "data for $k is $d";
}
}
else
echo "data for $key is $dat";
}
}
}
}
}
You can use foreach to loop through the arrays which have keys starting from 0 to n. So that you can foreach through the main array to get the datas array for all the keys. For getting rows childs you can use another foreach inside it to get each items. But for rows it is object , so you have to use -> to select the key. see below example code. But on your array the second array consist different formate in rows array. so make it like a common formate to loop through it easily.
For eg :-
foeach($parent_array as $array){
$data=$array['datas'];
$res = $data['res'];
$rows=$data['rows'];
foreach($rows as $row){
echo $row->a; // to get the value of key a = 11
}
}
I'm new to php and have been using the community and answers here to really help me with a little project I'm working on so thank you all in advance for the help so far!
I am pulling a load of information held in a poorly formatted text file/feed, trimming the contents of special characters and then using str_replace to find other specific strings and replace them with commas(,) or semi-colons(;), in order to create a usable piece of text. I then want to search this text for certain keywords and return other parts of the text in it's place.
So far, I've managed to explode the text into a multidimensional array, but I can't work out how to search this array now, in order to pull out a specific piece of information. I'm essentially trying to build a searchable array that I can pull information from as and when the original feed updates. Here's a sample of the array as it stands at the moment:
Array
(
[0] => Array
(
[0] => 240
[1] => 1
[2] => euro
[3] => 2016-02-19 15:30:00
[4] => EUR
)
[1] => Array
(
[0] => 240
[1] => 3
[2] => euro2
[3] => 2016-02-19 15:00:00
[4] => EUR
)
[2] => Array
(
[0] => 1890
[1] => 9
[2] => uspb
[3] => 2016-02-17 22:59:00
[4] => USD
)
)
Essentially, I want to be able to write something that will search this array for say uspb (array 2, key 2) and if it is found, return the value held under another key. So if I want key 0, it will return 1890. If I want key 1 when searching for euro2 it will return "3".
I've looked through a ton of examples and nothing really fits what I'm after at the moment. Perhaps I'm looking at this the wrong way and using an array isn't the correct approach. Any advice would be greatly appreciated.
For reference, here's a copy of my code (slight redacted) so far.
<?php
$file=file_get_contents("http://www.example.com/feed/");
$trim=trim($file, "[]");
$find = array("{\"value\":\"", "\",\"date_utc\":\"", "\",\"currency\":\"");
$replace = array(",", ",", "");
$replaced = str_replace($find, $replace, $trim);
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $replaced)
);
print_r ($ret);
?>
As your array is multidimensional - you have to iterate over it to find the value you need:
foreach ($ret as $value) {
// the index you want to search is always `2`?
if ($value[2] == 'uspb2') {
echo $value[0];
break;
}
}
And moving to function:
function findMyValue(
$array,
$search_key,
$search_str,
$key
) {
foreach ($array as $v) {
if ($v[$search_key] == $search_str) {
return $v[$key];
}
}
return 'NOT_FOUND';
}
echo findMyValue($ret, 2, 'euro', 1); // outputs 3
echo findMyValue($ret, 2, 'uspb', 0); // outputs 1890
And as already noticed in comments - it's not a poorly formated text, it's JSON. You can get an array from JSON string simply with json_decode function:
$file=file_get_contents("http://www.example.com/feed/");
$ret = json_decode($file, true);
var_dump($ret);
I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!
I've found this useful script to convert Google Spreadsheets into array.
https://github.com/VernierSoftwareTechnology/google-spreadsheet-to-php-array/blob/master/google-spreadsheet-to-array.php
The resulting array is in the form:
Array
(
[1] => Array
(
[A] => id
[B] => start_date
[C] => title
...
[2] => Array
(
[A] => 10551920077
[B] => 27/03/2014 19:00:00
[C] => Up and Down The City Road
)
and so on...
But I want the first row values to act as keys for the array, like:
Array
(
[2] => Array
(
[id] => 10551920077
[start_date] => 27/03/2014 19:00:00
[title] => Up and Down The City Road
)
and so on...
I've tried to modify the code, but with no success.
Any help?
Thanks in advance! :)
Rather than modifying someone else's code (which is often very difficult), it's probably easier to change the data after the fact:
// get the column headers
$headers = $data[1];
// walk the array and change the keys
$data = array_map(function($row) use($headers) {
// create an array to hold the new row
$new = array();
// step through the array keys...
foreach(array_keys($row) as $k)
// ...and add the new key to the new row with the old data
$new[$headers[$k]] = $row[$k];
// add the new row to the array
return $new;
}, $data);
// now remove the header row from the data
unset($data[1]);
There's probably a way (using some combination of array_walk, array_map or other array functions) to replace that ugly foreach loop in there.
i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.