Adding a new array to a multidimensional array item - php

I need to add some details to an array without overwriting the old data.
At the moment I have something like this if I print_r($data)
Array
(
[one] => Hello
[two] => Hello World
)
I then have a function that adds some data to the array
foreach ($rubric as $rs){
if($rs['position']==1){$data['one']=$rs;}
if($rs['position']==2){$data['two']=$rs;}
}
This gives me the following if I print_r($data)
Array
(
[one] => Array
(
[id] => 1
)
[two] => Array
(
[id] => 2
)
)
Does anyone have any ideas
What I would like to do is....
foreach ($rubric as $rs){
if($rs['position']==1){$data['one']['details']=$rs;}
if($rs['position']==2){$data['two']['details']=$rs;}
}
With the aim of adding a new subarray called "details" within each array item...
Does that make sense? If I try to run that code however I get the following error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Could someone tell me what I'm doing wrong?

See, array_push array_unshift.
Array push puts an element at the end. Array unshift adds a number to the beginning of the array.
You can also use the structure
$myArray['nameOfNewElement']=$newElement;
This adds $newElement to the array $myArray;

You can use array_merge.
According to your question, here is the solution :
// sample array
$rubric = array(0=> array("position"=>1),1 => array("position"=>2));
$data = array("one" => "Hello","two" => "hello world");
foreach ($rubric as $rs){
if($rs['position']==1){
$d= array_merge($data,$rs);
}
if($rs['position']==2){
$d= array_merge($data,$rs);
}
}
print_r($d);
Here is the working DEMO : http://codepad.org/rgKiv542
Hope, it'll help you.

When you write $data['one'] = $rs;, you are assigning $rs to overwrite the value "Hello".
Perhaps what you were trying to do is
$data['three'] = $rs['id'];

Related

Loops returning only one value from array

I have the following array that I converted from a JSON response of the WP REST API:
Array
(
[0] => Array
(
[id] => 6
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => John Doe
[email_do_convidado] => Array
(
[0] => johndoe#gmail.com
)
)
[1] => Array
(
[id] => 5
[convite_id] => Array
(
[0] => 4
)
[nome_do_convidado] => Lorem
[email_do_convidado] => Array
(
[0] => lorem#gmail.com
)
)
)
And I'm trying to loop the [email_do_convidado] value as:
johndoe#gmail.com
lorem#gmail.com
I've tried with foreach() loop and just get the last one, and now I've tried with while() and get one result too, follow my script:
while (list ($key, $val) = each ($myArray) ) echo $val['email_do_convidado'][$key];
And the result is:
johndoe#gmail.com
What I'm doing wrong here?
Try with a foreach instead of a while. You can extract all the emails by merging all arrays into a final output.
$emails = [];
foreach($myArray as $entry){
$emails = array_merge($emails, $entry['email_do_convidado']);
}
var_dump($emails);
I assume you'll want to do something afterwards will all the emails. I'll leave that up to you.
Its not quite clear, what i understand is that u want the first email of each element, if thats the case u could do this
foreach($array as $value){
echo $value[email_do_convidado][0];
}
On the other hand if u have several emails inside "email_do_convidado" u could loop that other array
foreach($array as $value){
foreach($value[email_do_convidado] as $email){
echo $email;
}
}
Or if u dont want to use a foreach inside a foreach u can
//inside the first foreach.
$emails = implode(',', $value[email_do_convidado]);
//and the u echo $emails
echo $emails;
Hope my answer helps u.
The values you are seeking are in:
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][0]
Your code is:
while (list ($key, $val) = each ($myArray) ) {
echo $val['email_do_convidado'][$key];
}
(slightly amended to better style)
So your code is trying to retrieve
$myArray[0]['email_do_convidado'][0]
$myArray[1]['email_do_convidado'][1]
The latter doesn't exist. So I'm afraid you have failed on multiple levels:
your code doesn't do what you intend
your error reporting is not working (PHP is throwing a warning about this you are not seeing)
you haven't attempted to instrument your code to see what's happening (simply putting "email=" before the value in your echo statement would have revealed this).
Try:
echo $val['email_do_convidado'][0];

How to output different levels of an array

As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand

PHP Array_unique value error in while loop

This is my PHP script for getting plan
This is my table
plan
3|6
6|12
3|12
and
<?php
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal=explode("|",$t_data['plan']);
print_r(array_unique($arrayVal));
}
?>
and I got the result is
Array ( [0] => 3 [1] => 6 ) Array ( [0] => 6 [1] => 12 )
Here I want 3,6,12 only. What is the problem in my script
before your while loop add this line:
$arrayVal = array();
and replace $arrayVal=explode("|",$t_data['plan']); with $arrayVal=array_merge($arrayVal, explode("|",$t_data['plan']));
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
$arrayVal = array();
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal = array_merge($arrayVal, explode("|",$t_data['plan']));
}
print_r(array_unique($arrayVal));
Note: When using array_merge with associated arrays, it will overwrite values for same keys, but when using numeric keys array_merge will not overwrite them instead append as new values.

how to get value from array with 2 keys

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.

PHP array problem, array_merge() does not solve the problem

How to solve array problem?
Excepted result:
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
[2] => 2011/02/21
)
Failed result that I get now:
Array
(
[0] => 2011/03/13
)
Array
(
[0] => 2011/03/14
)
Array
(
[0] => 2011/02/21
)
PHP code:
<?php
function get_dir_iterative($dir='.',$exclude=array('cgi-bin','.','..')){
$exclude=array_flip($exclude);
if(!is_dir($dir)){return;}
$dh=opendir($dir);
if(!$dh){return;}
$stack=array($dh);
$level=0;
while(count($stack)){
if(false!==($file=readdir($stack[0]))){
if(!isset($exclude[$file])){
if(is_dir("$dir/$file")){
$dh=opendir("$file/$dir");
if($dh){
$d=$file;
array_unshift($stack,$dh);
++$level;
}
}else{
if(isset($d)&&$level>0){
$mod=date('Y/m/d',filemtime("$d/$file"));
$ds="$d/";
}else{
$mod=date('Y/m/d',filemtime($file));
$ds='';
}
$array=array($mod);
//$b=array_merge($array); // it doesn't solve the problem
print_r($array);
}
}
}else{
closedir(array_shift($stack));
--$level;
}
}
}
get_dir_iterative();
?>
Update:
On replacing $array=array($mod); with $array[]=$mod; does not return excepted result.
Array
(
[0] => 2011/03/13
)
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
)
Array
(
[0] => 2011/03/13
[1] => 2011/03/14
[2] => 2011/02/21
)
array_merge() takes several parameters, the arrays that you want to merge, in your situation it should be:
array_merge($array, $mod);
// Or:
$array[] = $mod;
Note that you can simply add a new entry to your global array (second example) to add a value. Array_merge eats more memory than it needs.
$array=array($mod);
//$b=array_merge($array); // it doesn't solve the problem
print_r($array);
For one, array_merge requires at least two arrays to do its thing. You're only providing one, so there's nothing to merge with. Your "live" version creates a new array each time, so that's why you're getting the 'bad' output. Why not simply do
$array[] = $mod;
which'll append the file's mtime to the array on each iteration? You might want to store the file's details as well, so you know where the mtime's coming from, so
$array[$dir/$file] = $mod;
might be of more use.
You can achieve this by replacing this code: $array=array($mod); with this code: $array[]=$mod;.
Try replacing the commented out line with $b[] = $array

Categories