i'm trying to output data table with PHP multidimensional array, but i have problem with foreach loop it loops for only one index, it doesn't output next indexes, in my print_r output for $docs
Array
(
[docs] => Array
(
[0] => Array
(
[title] => Rew
[imgurl] => http://localhost/site/uploads/2012/07/print.jpg
[level_id] => Array
(
[0] => 2
[1] => 3
)
)
[1] => Array
(
[title] => Second
[imgurl] => http://localhost/site/uploads/2012/07/type.jpg
[level_id] => Array
(
[0] => 1
[1] => 3
)
)
)
)
in my php
$i =0;
foreach ($docs as $doc){
foreach($doc as $a_doc){
foreach($doc as $a_doc){
echo $doc[$i]['title'];
}
}
$i++;
}
but it doesn't give any output,i would REALLY appreciate if someone could give me some advice.
If the array containing the docs key only has a single element, you can do this:
foreach( $docs['docs'] as $doc ) {
echo $doc['title'];
}
If it should have more than one entry (besides docs), go for:
foreach( $docs as $entry ) {
foreach( $entry as $doc) {
echo $doc['title'];
}
}
Try this:
foreach($docs as $key => $doc){
echo $doc['title'];
}
Each $doc that is iterated is an array of doc attributes. The $key in the foreach() loop is the currently indexed key for the currently iterated element in the $docs array.
Related
Ok so I have an array look like this,
Array
(
[0] => Array
(
[0] => order_date.Year
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date.Quarter
[1] => =
[2] => 1
)
)
What I want to do is, in any element of this multidimensional array I want to replace any string that have a . with removing everything after .
So the new array should look like this,
Array
(
[0] => Array
(
[0] => order_date
[1] => =
[2] => 2024
),
[1] => Array
(
[0] => order_date
[1] => =
[2] => 1
)
)
I have tried doing this,
foreach ($filter as $key => $value) {
if(is_array($value)) {
$variable = substr($value[0], 0, strpos($value[0], "."));
$value[0] = $variable;
}
}
print_r($filter);
I'm getting $value[0] as order_date but can't figure out how to assign it to $filter array without affecting other values in array;
The $value variable is not linked with the original array in the foreach loop.
You can make a reference to the original array by using ampersand "&"
foreach ($filter as $key => &$value) { ... }
Or you can use old school key nesting
$filter[$key][0] = $variable;
Please take a look here https://stackoverflow.com/a/10121508/9429832
this will take off values after . in every element of any multidimensional array.
// $in is the source multidimensional array
array_walk_recursive ($in, function(&$item){
if (!is_array($item)) {
$item = preg_replace("/\..+$/", "", $item);
}
});
I have two arrays- one single and other multi-dimensional.
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
echo '<pre>';
print_r($jkl);
echo '</pre>';
echo '<pre>';
print_r($ghi);
echo '</pre>';
And this is what it looks like:
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
Array
(
[0] => Array
(
[post_id] => 1
[postid] => 42
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => jordan
)
)
[1] => Array
(
[post_id] => 3
[postid] => 38
[tags] => Array
(
[0] => abc
[1] => def
[2] => jordan
)
)
[2] => Array
(
[post_id] => 4
[postid] => 40
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => first
[3] => second
[4] => fourth
)
)
)
What I am trying to do is search for the elements of single-dimensional array inside the sub-array tags present in the multi-dimensional array.
This is my code:
$users = array_unique($jkl);
$array = [];
$i=0;
foreach($users as $user)
{
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
$i++;
}
But I get the error mentioned as the question title.
What could be the possible reason? Thanks!
You have to iterate through multi-dimensional array and do what you want:-
<?php
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
$users = array_unique($jkl);
$array = []; // empty array
foreach($ghi as $gh) // iterate through multi-dimensional array not single one
{
for($i=0;$i<count($users);$i++){ // a for loop to iterate through single-dimensional completly
if (in_array($users[$i],$gh['tags'])) // if single dimensional array value exist in multi-dimensional tags array
{
$newdata = array (
'postId' => $gh['postid'],
'tag' => $users[$i]
);
array_push($array, $newdata); // push the data
}
}
}
echo "<pre/>";print_r($array); // print newly created array
?>
Output:-https://eval.in/602523
Note:- Try to put variable name in such a way that they don't produce ambiguity.Thanks
Your both array has different numbers of elements. first array has four elements while second array has three elements. that's why you are getting problem.
You should check variable is set and must be an array. Use !empty() and is_array()
foreach($users as $k=>$user){
if(!empty($ghi[$k]['tags']) && is_array($ghi[$k]['tags'])) { // check this condition here
if (in_array($user, $ghi[$k]['tags'])){
$newdata = array (
'postId' => $ghi[$k]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
Note:- I have used array key as $k instead of $i
This is because length of your 2 arrays are different, use isset() to remove error:
as 3rd index of your $ghi array does not exist, and its trying to fetch $ghi[3]['tags'] - that's why error is occurring
Try:
foreach($users as $user)
{
if(isset($ghi[$i]['tags'])) { // just add this condition here
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
$i++;
}
It depends on what you are searching for.
If you want to examine ALL of the $users against ALL of the $ghi array then you need to loop over both each time.
foreach($users as $user)
{
for ($i = 0; $i < count($ghi); $i++) {
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
This will result in the $newdata consisting of the following
array(2) { ["postId"]=> string(2) "40" ["tag"]=> string(6) "fourth" }
But if you only want to examine the each array against the other once. Then you need to check to make sure you're not going out of bounds.
$ghi only has 3 elements in it.
there are 4 elements in $users.
So you can either loop through the smaller array in your foreach - switch $users -> $ghi
or check inside the foreach loop that $ghi has a valid element at whatever $i is.
D.
I have an array which is the result of a select query using Amazon SimpleDb.
Here is sample data when I print_r($result);
Array ( [0] => Array ( [Name] => 5140ede647e74
[Attributes] => Array (
[0] => Array ( [Name] => test_id [Value] => 5140ede647e74 )
[1] => Array ( [Name] => test_name [Value] => test1 )
[2] => Array ( [Name] => last_update [Value] => 1363209702 )
[3] => Array ( [Name] => created [Value] => 1363209702 ) ) ) )
If I want to extract the test_id and the test_name, how can I do it? I am currently doing the following
<?php foreach ($result as $item) {
echo $item['Attributes'][0]['Value'];
echo $item['Attributes'][1]['Value'];
} ?>
But I want to do it by referencing "test_id" and "test_name" because when I delete the domain where the data resides and re-enter the data, the order of each attribute can change so I can't trust that $item['Attributes'][0]['Value'] will always be the test_id
Thanks!
foreach ($result as $item) {
foreach ($item['Attributes'] as $keyvalue) {
if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
echo $keyvalue['Value'];
}
}
}
You need to recast the Array.
$newArray = array();
foreach ($result as $key=>$row)
{
foreach ($row['Attributes'] AS $row2)
{
$newArray[$key][$row2['Name']] = $row2['Value'];
}
}
EDIT: It depends on what you need to do - this is my preferred method if I plan on doing a lot of work with a resultset - I only need to iterate through the set once and then it's in a format where the data can be accessed quickly.
The following will run trough the last part of your array by reference. Therefore edits that you make are reflected in the $result array.
foreach ($result[0]['Attributes'] as &$item) {
if ($item['Name'] == 'test_id') // do something
}
There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.
I have an array that looks like this:
$array = Array ( [0] => Array ( [site_id] => 89193)
[1] => Array ( [site_id] => 89093)
[2] => Array ( [site_id] => 3059 )
)
What I want to do is to add a new pair to the array, how can I do so?
For example, next to site_id, I want to add the key [site_name] and its value.
foreach ($array as &$child) {
$child['site_name'] = $value;
}
or, without references:
foreach (array_keys($array) as $key) {
$array[$key]['site_name'] = $value;
}