Create Main Array that includes multiple child array - php

How Can I Create a main array that includes multiple child array And be in the form of Jason and I want to add the child Array to main array in the Loop
MainArray=[
array1=[{fname:asdada,lastname:sdsadasda}];
array2=[{fname:asdada,lastname:sdsadasda}];
array3=[{fname:asdada,lastname:sdsadasda}];
];
echo MainArray[1]->fname;
Please see the following pseudo code below:
pseudo code

You should really look into a basic php tutorial.
This is how you do it.
$mainArray = [
'array1' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array2' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array3' => ['fname' => 'asdada', 'lastname' => 'sdsadasda']
];
echo $mainArray['array1']['fname'];
Or use the long notation if you have an older version of php or want backwards compatibility.
$mainArray = array(
'array1' => array('fname' => 'foo', 'lastname' => 'bar'),
'array2' => array('fname' => 'lorem', 'lastname' => 'ipsum'),
'array3' => array('fname' => 'test', 'lastname' => 'example')
);
echo $mainArray['array1']['fname'];
Explanation:
The php variable sigil is $. This means that in order to access a variable or assign something to a variable, you use $mainArray. See more on variables in the documentation.
The php array can be used in two different notations. Either array(...) or, from php 5.4 upwards, [...]. Other than the opening and closing parts, they are identical. You don't use : or = to assign individual values inside an array declaration. For this you use the => operator. Each element in an array is separated by a comma (,).
E.g.
$mainArray = array(
'A' => 1,
'B' => 2
];
Arrays in Php can be either associative or numerical. What you probably want is that your outer array is numerical, meaning you can access it using $mainArray[1], and your inner array is associative. For numerical arrays, you don't specify a key yourself, so there is no need for the =>.
$mainArray = array(
array(),
array(),
array()
);
And with associative sub arrays this becomes:
$mainArray = array(
array('firstname' => 'foo', 'lastname' => 'bar'),
array('firstname' => 'test', 'lastname' => 'example'),
array('firstname' => 'lorem', 'lastname' => 'ipsum')
);
In order to access the firstname key of the first child array in this multilevel array structure, you do:
$mainArray[0]['firstname']
E.g. (if you want to echo it to the standard output)
echo $mainArray[0]['firstname'];
Please note that numerical arrays in php start counting on 0, as in most other programming languages. And please note that the key in the associative array is a string, and as such must be surrounded with either ' or ".
I can recommend you search for a php beginner's tutorial and try to write and execute the examples yourself, to get a better grasp of php. If you need somewhere to run your php examples, I can recommend you try an online php environment such as PHPFiddle.
Update on adding values:
You can add more key=>value pairs to an associative array or add more values to a numerical array afterwards in much the same way as you would access or assign to it.
First, let's add a value to a numerical array. You do this by adding [] to the end of your variable when assigning. This means that what you assign will be added as a new numerical value to the end of your array.
$numericalArray = array(
7,
8,
6,
12,
'B'
);
$numericalArray[] = 'C';
// Results in the array: array(7, 8, 6, 12, 'B', 'C')
And in order to add a new key => value pair to an associative array, you just add it using the new key, e.g.
$assoc = array(
'firstname' => 'Testy',
'lastname' => 'McTestface'
);
$assoc['middlename'] => 'Tester';
So to add a new fname-lastname pair to the mainArray, you would do:
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
$mainArray[] = array('fname' => 'new name', 'lastname' => 'new last name');
If you want to do this in a loop, you will use the for, foreach, while or do while structures.
E.g.
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
for ($i = 0; $i < 3; ++$i) {
$mainArray[] = array('fname' => 'new name ' . $i, 'lastname' => 'new last name ' . $i);
}
echo json_encode($mainArray, JSON_PRETTY_PRINT|JSON_UNESPACED_UNICODE|JSON_UNESCAPED_SLASHES), PHP_EOL;
// [
// {'fname': 'foo', 'lastname': 'bar'},
// {'fname': 'test', 'lastname': 'example'},
// {'fname': 'lorem', 'lastname': 'ipsum'},
// {'fname': 'new name 0', 'lastname': 'new last name 0'},
// {'fname': 'new name 1', 'lastname': 'new last name 1'},
// {'fname': 'new name 2', 'lastname': 'new last name 2'},
// ]

Related

Create array of key => value thanks to "helper" functions

I have an 2 dimensional array with this values :
[
'id' => 12,
'title' => 'the title', //and a few other key => value
],
[
'id' => 13,
'title' => 'the title 13', // and a few other key => value
],...
In the end, I need to have a multidimensional array only with id and title
[ $item['id'] => $item['title'], ...]
Usually, I'm doing a simple foreach to achieve this, but I want to use php function now. I've done this, but is there a proper way to do this?
$list = array_combine(array_column($list_forms, 'id'), array_column($list_forms, 'title'));
With third argumenf of array_column it is:
$list = array_column($list_forms, 'title', 'id');

Merge arrays by suffix of keys PHP

I have two arrays, that I want to merge as one according to keys suffix.
$keys = array(
'staff_first_name' => NULL,
'staff_last_name' => NULL,
'staff_years' => NULL
);
$submitted_values = array(
'first_name' => 'jon',
'last_name' => 'doe',
'years' => 5
);
I understand I could use a function like shown here and modify it.
But is there a native php function that will accomplish this. I attempted to use array_merge_recursive but after reviewing the documentation It will not do what I need it to.
$wanted_array = array(
'staff_first_name' => 'jon',
'staff_last_name' => 'doe',
'staff_years' => 5
);
If you know the two arrays are the same size, and in the same order, you can use array_combine with array_keys.
$wanted_array = array_combine(array_keys($keys), $submitted_values);
Because it's a suffix that is the same on each key we don't need to worry about it.
If we ksort the arrays they should both be sorted the same because the suffix is the same on all in key array.
$keys = array(
'staff_first_name' => NULL,
'staff_last_name' => NULL,
'staff_years' => NULL
);
$values = array(
'years' => 5,
'first_name' => 'jon',
'last_name' => 'doe',
);
ksort($values);
ksort($keys);
Var_dump(array_combine(array_keys($keys), $values));
I intentionally placed years first to show that it works.
https://3v4l.org/cBNhk
If you need to reduce the $_POST to only these array items to be able to combine them you can use a combination of preg_grep, array_flip, array_values and array_intersect_key to filter out the wanted items from the array.
$val = preg_grep("/first_name|last_name|years/",array_values(array_flip($values)));
$values = Array_intersect_key($values, array_flip($val));
ksort($values);
ksort($keys);
Var_dump(array_combine(array_keys($keys), $values));
I added some extra items to simulate a larger mixed $_POST array.
https://3v4l.org/a3ju1
This is one of those questions where I must implore the OP to rethink their process. It only complicates your code to introduce associative keys that do not instantly synchronize with your form field names. This is the best advice that I can give you: declare a whitelist of keys and assign default values to each, then filter, then replace.
Since your values are all null, your code can be made more DRY by calling array_fill_keys().
The following can be written as one line of code, but to show each step, I've printed the arrays to screen after each function call.
Code: (Demo)
$defaults = array_fill_keys(['first_name', 'last_name', 'years'], null);
var_export($defaults);
$_GET = [
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5
];
var_export($_GET);
$screened = array_intersect_key($_GET, $defaults);
var_export($screened);
$replaced = array_replace($defaults, $screened);
var_export($replaced);
Output:
array (
'first_name' => NULL,
'last_name' => NULL,
'years' => NULL,
)array (
'last_name' => 'doe',
'Hackers' => 'can be naughty',
'years' => 5,
)array (
'last_name' => 'doe',
'years' => 5,
)array (
'first_name' => NULL,
'last_name' => 'doe',
'years' => 5,
)
...p.s. makes sure that you use prepared statements with placeholders if you are sending any of the values to the database.

How to get id as key and email as its value from multidimensional array?

I have multi-dimensional array like below
$records = array(
array(
'id' => 11,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john#gmail.com'
),
array(
'id' => 12,
'first_name' => 'Sally',
'last_name' => 'Smith',
'email' => 'sally#gmail.com'
),
array(
'id' => 13,
'first_name' => 'Jane',
'last_name' => 'Jones',
'email' => 'jane#gmail.com'
)
);
Now,I want the output as array in form of id as key and email as its value.
Array
(
[11] => john#gmail.com
[12] => sally#gmail.com
[13] => jane#gmail.com
)
I want short code for it, Not want any lengthy code.
I have tried it with foreach
$collect_data = array();
foreach($records as $key=>$data){
$collect_data[$data['id']] = $data['email']
}
Any one know short code for above to achieve my requirement.
I think, You can try php in-build function to sort out your solution
$emails = array_column($records, 'email', 'id');
print_r($last_names);
You can also refer following link too.
Php In-build Function (array_column)
This should work for you:
Just array_combine() the id column with the email column, which you can grab with array_column().
$collect_data = array_combine(array_column($records, "id"), array_column($records, "email"));
For compatibility sake, as array_column was introduced in PHP 5.5, consider array_reduce:
$output = array_reduce($records, function($memo, $item){
$memo[$item['id'] = $item['email'];
return $memo;
}, []);
I find it more expressive than a foreach, but that's matter of personal taste.

How to turn sql result to multi-dimensional array dynamically?

Here is the query string.
$query = "SELECT t.id, t.assignee, t.owner,
d.code, d.status, d.target_completion_date,
d.target_extension_date, d.submission_date, d.approval_date,
d.revision_start_date, d.revision_completion_date, d.message,
ty.name, f.orig_name, f.new_name,
b.payment_date, b.discount, b.total_cost, b.amount_payed, b.edit_level,
b.billing_type, b.pages, b.words
FROM tasks t
INNER JOIN details d ON t.detail_id = d.id
INNER JOIN billing b ON t.billing_id = b.id
INNER JOIN TYPE ty ON d.document_type_id = ty.id
INNER JOIN files f ON t.file_id = f.id
WHERE t.assignee = 'argie1234'";
And this is the array i would like the query result to turn into.
$user = array('allTask'=>array(array('taskid' => 1,
'assignee'=>'argie1234',
'owner'=>'austral1000',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' =>'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
array('taskid' => 12,
'assignee'=>'argie1234',
'owner'=>'usaroberto',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' => 'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
'account' => array( 'username' => 'marooon55',
'emailadd' => 'marooon#yahoo.com',
'firstname' => 'Maroon',
'initial' => 'E',
'lastname' => 'Young',
'country' => 'Australia',
'gender' => 'M',
'password' =>'360e2801190744a2af74ef6cbfdb963078b59709',
'activationDate' => '2013-09-13 14:30:34') );
How can i create the above array? I sure know how to define multi dimensional array, regretfully though i am having difficulty creating this complex array dynamically. As a beginner i don't even know where to begin.
Here is an example that might help you out. Try starting with simple multi dimensional arrays, once you get a hold of it, you can move onto building complex ones. You will then find that the array you want to build is not really difficult than you initially thought it to be.
$mycomplexarray = array('key1' => array('val1', 'val2'),
'key2' => array('val3', 'val4' => array('val5', 'val6')
)
);
You could create the array just as you have here. I'm not gonna write the whole thing out, but something like this...
$result = $mysqli->query($query); // however you query the db is up to you.
$row = $result->fetch_assoc(); //same as query use your prefered method to fetch
$user = array('allTask'=>array(array('taskid' => $row['id'],
'assignee'=>$row['assignee'],
'owner'=>$row['owner'],
'details' => array( 'code' => $row['code'],
'status'=>$row['status'],
...etc, Hope this makes sense for you.
Set up a structure array first that defines which columns will be stored in a sub array like
$struc=array('Id'->0, 'assignee'->0, 'owner'->0,
'code'->'detail', 'status'->'detail', 'target_completion_date'->'detail',
'target_extension_date'->'detail', 'submission_date'->'detail', 'approval_date'->'detail',
'revision_start_date'->'detail', 'revision_completion_date'->'detail', 'message'->'detail',
'name'->'file', 'orig_name'->'file', 'new_name'->'file',
'payment_date'->'billing', 'discount'->'billing', 'total_cost'->'billing', 'amount_payed'->'billing', 'edit_level'->'billing', 'billing_type'->'billing', 'words');
In your while ($a=mysqli_fetch_assoc($res)) loop you can now use this structure to decide whether you want to store an element directly in your target array or whether you want to place it in the subarray named in this structure array. Like
$res=mysqli_query($con,$sql);
$arr=array();
while($a=mysqli_fetch_assoc($res)) {
// within result loop: $a is result from mysqli_fetch_assoc()
$ta=array(); // temp array ...
foreach ($a as $k => $v){
if ($struc[$k]) $ta[struc[$k]][$k]=$v;
else $ta[$k]=$v;
}
$arr[]=$ta; // add to target array
}
This is the complete code, no more is needed. It was typed up on my iPod, so it is NOT tested yet.
The generated array should be equivalent to your $user['allTask'] array.

Recursively merge two arrays, or replace with latter based on a key

This should be a really easy answer and I'm probably just being thick, but I have two arrays in PHP:
$data1 = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 3,
),
);
$data2 = array(
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
And I want to result in:
$result = array(
array(
'qid' => 'q-prof-1-1',
'value' => 10,
),
array(
'qid' => 'q-prof-2-1',
'value' => 5,
),
array(
'qid' => 'q-prof-3-2',
'value' => 1,
),
);
... so that the two will be merged- but, if it finds a qid that matches another, will replace it with the latter.
I've tried a mixture of array_merge(), array_merge_recursive(), $data1 + $data2, $data2 + $data1, array_replace(), array_replace_recursive(), array_diff() etc, etc, but every options seems to return either two or four values rather than the three. And of course I've done my fair share of S.O hunting.
Any ideas? Would prefer something short and sweet to a massive iterating function of any sort!
Thanks in advance :)
Matt
Edit:
I've just realised that if I turn the arrays inside $data1 & $data2 into key-value pairs most of those merge and replace functions work, eg:
$data1 = array(
'q-prof-1-1' => array(
'qid' => 'q-prof-1-1',
'value' => 10,
) // ... etc etc
);
... but I'd still rather not have to change the original data
Is there a reason you can't use an associative array? That way you can just have
$array = array('q-prof-1-1' => 10, 'q-prof-2-1' => 3);
$array2 = array('q-prof-2-1' => 5, 'q-prof-3-2' => 1);
Then just loop through $array2, push the value on if $array doesn't have a key (key_exists() if i remember right) or if it does have a key merge them how you want?
Also, but not sure, using an associative array would probably make array_merge work correctly (possibly).

Categories