I'm pulling JSON information and I'm left with a huge nested array.
An example schema is as follows:
'messages' =>
'0' =>
'title' => 'foo'
'body' => 'bar'
'1' =>
...
'stories'
'foo' => 'bar'
In this scenario, I only want to grab contents from starting with '0' and '1' and all of their children (title and body). 'stories' would be completely disregarded as it is one depth higher than 0 and 1. 0 and 1 is an automatically generated list and the integer value will dynamically go as high as need be, so it will be different.
Cheers!
foreach($array['messages'] as $key => $val){
if($key == 0 OR $key == 1){
$new_array[] = $val;
}
}
$new_array will then have the relevant content. This assumes that you're referring only to the messages part of the array. If there are other sub arrays that you want to parse/manipulate then you will have to adjust the condition in the foreach loop.
You can then parse/manipulate $new_array as needed, and ignore the content that you don't need in $array.
Related
I have this array:
$datas = array(
array(
'id' => '1',
'country' => 'Canada',
'cities' => array(
array(
'city' => 'Montreal',
'lang' => 'french'
),
array(
'city' => 'Ottawa',
'lang' => 'english'
)
)
)
);
Question 1:
How can I get the the country name when I have the id ?
I tried: $datas['id'][1] => 'country'
Question 2:
How can I loop in the cities when I have the id ?
I tried:
foreach ($datas as $data => $info) {
foreach ($info['cities'] as $item) {
echo '<li>'.$item['city'].'</li>';
}
}
Thanks a lot.
You have the ID of the array you want analyse, but your array is structured as a map, meaning that there are no keys in the outer array. You will therefore have to iterate the array first to find the object you are looking for.
While the first approach would be to search for the object that has the ID you are looking for, i suggest you map your arrays with their IDs. To do that, you can use two PHP array functions: array_column and array_combine.
array_column can extract a specific field of each element in an array. Since you have multiple country objects, we want to extract the ID from it to later use it as a key.
array_combine takes two arrays with the same size to create a new associative array. The values of the first array will then be used as keys, while the ones of the second array will be used as values.
$mappedCountries = array_combine(array_column($datas, 'id'), $datas);
Assuming that the key 1 is stored in the variable $key = 1;, you can afterwards use $mappedCountries[$key]['country'] to get the name of the country and $mappedCountries[$key]['cities'] to get the cities, over which you can then iterate.
if there might be many arrays in $datas and you want to find one by id (or some other key) you can do something like this:
function search($datas, $key, $value) {
foreach($datas as $data) {
if ($data[$key] === $value) {
return $data;
}
}
So if you want to find where id = 1
$result = search($datas, 'id', '1');
and then you can get country echo $result['country'] or whatever you need.
I am trying to produce a HTML list grouped by "groupName" from the array below.
array (size=30)
0 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Class' (length=11)
'txt' => string '............' (length=32)
'ID' => string '6' (length=1)
1 =>
array (size=4)
'groupOrder' => string '1' (length=1)
'groupName' => string 'Size' (length=11)
'txt' => string '..................' (length=34)
'ID' => string '6' (length=1)
2 =>
...
So I'd like produce something like this pseudo list:
groupName
txt
txt
txt
next GroupName
txt
txt
...
So my code looks like this
foreach ($datafeed as $val => $row) {
if (($datafeed[$val]['groupName']) == next($datafeed[$val]['groupName'])) {
//same group - do nothing
} else {
echo $datafeed[$val]['groupName'];
}
echo "<li>".$row['txt']. "</li>";
}
But I'm getting errors about "next() expects parameter 1 to be array, string given".
I've tried all sorts of different syntax, but I'm not making much progress. How do I compare two values in a nested array?
You misinterpreted the meaning of the function next(): you cannot query it for an array element. It manipulates the internal array pointer tied with the array itself, not with some its element. From the PHP documentation:
Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.
and see also a description of next.
Since the foreach loop crucially depends on the value of the array pointer, messing with the array pointer will ruin the loop: you probably see every second element in the loop, because at every iteration once next() is called by your foreach loop and then once by yourself.
The simplest thing for you is probably to use the old good for loop:
for ($i = 0; $i < length ($array); $i++)
{
if ($i == 0 || $array[$i] != $array[$i - 1])
echo "New group!\n";
echo $array[$i];
}
This doesn't answer your question directly, but you'd be better off restructuring your array so that they're grouped, and you don't need to perform any logic within the loop to check the groupName. Currently, you're relying on the next groupName to match the current groupName, but if they're not sequential, they won't be grouped.
You could do something like this:
$output = array();
foreach ($datafeed as $feed) {
$output[$feed['groupName']][] = $feed;
}
Here's a demo
You should not use next inside a foreach loop anyway, since you'll get conflicting array pointer movements. Simply store the last value:
$last = null;
foreach (...) {
if ($last != $row['current']) {
// new group
}
$last = $row['current'];
...
}
I have an array thus (got this using var_dump):
array
0 =>
array
'post_id' => string '6' (length=1)
1 =>
array
'post_id' => string '9' (length=1)
I want to get the key when I have just the post_id. For example, I want '0' returned if I have '6' and '1' if I have '9'. I have tried:
$key = array_keys($subs, array_keys($subs[??], 6));
given that the $subs is the array. The issue is, I don't know how to iterate through the array 'within' the 'parent' array, hence, the '??'
I would use array_filter() and use to do this. Like this:
$array; // your array
$needle; // the value you are looking for
$filtered_array = array_filter($array, function ($element) use ($needle) {
return ($element['post_id'] === $needle);
});
$matching_keys = array_keys($filtered_array);
The array_filter() will filter down the input array to only those array element arrays that have a value for post_id that matches the value of $needle. You can use array_keys to get the key values for the remaining element(s) after the filter has been applied.
$post_id_to_find = '6';
$key = '';
foreach ($subs as $k1 => $v1)
{
foreach ($v1 as $k2 => $v2)
{
if ($post_id_to_find == $v2)
{
$key = $k1;
break;
}
}
}
Essentially what this code does is loop through the outer array and for each element loop through inner array, and if it finds the post id you want it'll set a variable that was initalized outside of the loops so after you break out of the loops you'll have the appropriate key.
EDIT
This is actually a pretty crappy answer, I realized you don't really need the inner loop since you know what key you want to check in the inner arrays... Anyway it seems like you used another answer, so this is pretty much moot.
I have a an array that has 3 values. After the user pushes the submit button I want it to replace the the value of a key that I specify with another value.
If I have an array with the values (0 => A, 1 => B, 2 => C), and the function is run, the resulting array should be (0 => A, 1 => X, 2 => C), if for example the parameter for the function tells it to the replace the 2nd spot in the array with a new value.
How can I replace a specific key's value in an array in php?
If you know the key, you can do:
$array[$key] = $newVal;
If you don't, you can do:
$pos = array_search($valToReplace, $array);
if ($pos !== FALSE)
{
$array[$pos] = $newVal;
}
Note that if $valToReplace is found in $array more than once, the first matching key is returned. More about array_search.
In case you want to have an inline solution you can use array_replace or array_replay_recrusive depending on which suits you best.
$replaced_arr = array_replace([
'key' => 'old_value',
0 => 'another_untouched_value'
],[
'key' => 'new_value'
]);
It would be best if your array is key/value pair
Which of the following two data structures is "better"?
array('key'=>array(1,2,3,4))
OR:
array('key',array(1,2,3,4))
i.e., is it better to store the array as the second element in a two element array, or as the single element in an array with the key, 'key'.
Assume that for my purposes, in matters of convenience, they are equivalent. I am only curious whether one uses more resources than the other.
You use whichever one is appropriate for what you're trying to store.
If the key relates to the array of values and its unique then use key/value.
Worrying about resources used in this kind of situation are micro-optimizations and an irrelevant distraction.
if that's the full size of the array, then that's fine.
However, if you actually have an array like
array(
array('key', array(...)),
array('key', array(...)),
array('key', array(...)),
etc
);
instead of
array(
'key' => array(...),
'key' => array(...),
'key' => array(...),
);
Then it's not only odd, it's very unreadable.
The beaut thing of having named key to value is this:
"I want the value of Bob"
$bob = $myArray['bob'];
instead of
foreach($myArray as $key => $value) {
if ($value[0] === 'bob') { // the first value of your 2nd type
$bob = $myArray[1]; // get the next value.
}
}
Of course, for the 2nd example you could consider end(). But compare the 2, it is obvious the first example wins!