PHP function for adding sub-array to a multi-dim array - php

I am having trouble finding the right function for this.
I have a session array
$_SESSION['cart_items'][0] = (
'item_name'=>'some name',
'item_price'=>'29.99',
...
)
I need to append another array that has a specific key. The array is from a $_POST object.
$_POST['copy'] = array (
'name'=>'my name',
'office'=>'my office'
)
Appended session to look like this.
$_SESSION['cart_items'][0] = (
'item_name'=>'some name',
'item_price'=>'29.99',
...
'copy'=>array(
'name'=>'my name',
'office'=>'my office'
)
)
I tried array push but this gives me an indexed key for the appended array instead of 'copy'
I know the index of the parent array so i could create the new sub array and then loop the $_POST into it but that doesn't seem right either.

I might be missing the point - but cant you just do:
$_SESSION['cart_items'][0]['copy'] = $_POST['copy'];

$_SESSION['cart_items'][0][$key] = $_POST[$key]; // as you said you know the key .. is it only one?

Related

sort array based on other array sort

I have an array as follows:
$aq=['jonathan','paul','andy','rachel'];
Then I have an array as follows:
$bq=['rachel','andy','jonathan'];
What I need is to use the ordering of the first array to sort my second array.
So for this instance, the resulting sorted array should be:
$cq=['jonathan','andy','rachel'];
I started working on a solution that uses the highest key as the top value (the head of the array) because what Im looking for is the top value but that ran into issues and seemed more like a hack so i think sorting is what im looking for.
Is there a simple function in php that can sort my data based on my first array and there respective positions in the array
please try this short and clean solution using array_intersect:
$aq = ['jonathan','paul','andy','rachel'];
$bq = ['rachel','andy','jonathan'];
$cq = array_intersect($aq, $bq);
var_export($cq);
the output will be :
array ( 0 => 'jonathan', 2 => 'andy', 3 => 'rachel', )
You'll have to use a custom sort function. Here we grab the keys of corresponding entries in the "ordering" array and use them to order the working array.
In this example, we give up (return 0) if the key doesn't exist in the ordering array; you may wish to customize that behavior, but this should give you the general idea.
$order = ['jonathan','paul','andy','rachel'];
$arrayToSort =['rachel','andy','jonathan'];
usort($arrayToSort,function($a,$b) use ($order){
if( ! array_key_exists($a,$order) ) return 0;
if( ! array_key_exists($b,$order) ) return 0;
if( array_search($a,$order) > array_search($b,$order)
return 1;
return -1;
});

PHP push new key and value in existing object array

In my study how objects and arrays work with PHP I have a new problem. Searching in existing questions didn't give myself the right "push".
I have this for example:
$html_doc = (object) array
(
"css" => array(),
"js" => array()
);
array_push($html_doc , "title" => "testtitle");
Why is this not working? Do i need to specify first the key title? Or is there another "1 line" solution?
array_push() doesn't allow you to specify keys, only values: use
$html_doc["title"] = "testtitle";
.... except you're not working with an array anyway, because you're casting that array to an object, so use
$html_doc->title = "testtitle";
You can simply use $html_doc["title"] = "testtitle";
Check this comment on the array_push manual page.

In PHP, how can I access a child object when I don't know it's name?

Using json_decode, I've ended up with an object that looks like this:
$data->foo->bar->1234567->id
I want to access id. There are two problems, both with the number 1234567:
It's an illegal property name.
The number will differ each time, and I can't predict what the number will be. I need a way of accessing id, even when I don't know the number.
I know I can overcome problem (1) with curly braces, but I don't know how to overcome (2). I don't want to use get_object_vars, because the object is likely to be very large, and that function is very slow.
My current solution is simply
foreach ($data->foo->bar as $id); but that feels rather hacky. Is there a better way?
From my comment above, using json_decode(,true) and then resetting.
The example json array looks like:
Array (
[foo] => Array (
[bar] => Array (
[1234567] => Array (
[id] => 1234
)
)
)
)
The code:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
reset($data['foo']['bar']);
$number = key($data['foo']['bar']);
echo $data['foo']['bar'][$number]['id'];
Output: 1234
In case you don't need the whole array anymore and only want to get the id you can get it like this:
<?php
$data = json_decode('{"foo":{"bar":{"1234567":{"id":1234}}}}', true);
echo array_shift($data['foo']['bar'])['id'];
Only works if the unknown key is the first element of bar. array_shift removes the element from $data.

Put a Array in another Array by comparing their values

I got two arrays. Array A with Soccer-Player positions and array B with Soccer-Players.
Every Player got a name and a position.
Now I wanted to split array B in the different postions of array A and re-order it in one array sorted like the positions in array A.
The arrays look like this:
Array A
Array ( tor,
abwehr,
mittelfeld,
sturm )
Array B
Array ( Array ( Rocky, Sturm ),
Array ( Kevin, Abwehr ) )
My result array should look like this:
Array ( tor,
abwehr(Array ( Kevin, Abwehr )),
mittelfeld,
sturm(Array ( Rocky, Sturm )) )
My code till now:
$positionen = array("tor", "abwehr", "mittelfeld", "sturm");
foreach($positionen as $position) {
$team = $extern_source->api();
foreach($team['data'] as $team) {
//need to explode this to filter relevant infos
$team_info = explode("\n",$team['info']);
$sp_name=$team_info[1];
$sp_posi=$team_info[4];
//put together the single infos in a new array
...
I really hope you understand my problem.
It put knots in my brain. so complicated :D
Thank you very much!
Best regards from Germany.
foreach($arrayB as $player){
$position[$player[1]][] = $player[0];
}
First prepare the final array before the first foreach:
$data = array_fill_keys($positionen, array());
Then after feching the name and the position, do this:
$data[$sp_posi][] = $sp_name;
Note: array_fill_keys requires PHP 5.2 or higher

Converting an array into a usable string - cakePHP

I'm working on a simple cakePHP form. I have a variable $user_name that's populated from my SQL tables.
I've affirmed with
echo '<pre>';
print_r($user_name);
echo '</pre>';
That the $user_name is correctly populated. I'm trying to use the variable that I've populated to auto-fill the following form field
echo $this->Form->input($modelNameField . '.name_of_customer', array('readonly'=> 'readonly','label'=> 'Customer Name', 'type'=> 'text', 'value'=> $user_name));
However, the field remains blank. Any suggestions?
Declaration for $user_name
App::import('model','customerInfo');
$customerInfos = new customerInfo();
$user_name = array();
$user_name = $customerInfos->get_name($id);
--
The get_name method
public function get_name($id)
{
return $this->find('first', array('fields' =>array('usr_name'),'conditions'=>array("customerInfo.id"=>$id)));
}
--
The print out from print_r($user_name); for $id =1 is
Array
(
[CustomerInfo] => Array
(
[usr_name] => Ted Jones
)
)
This is a pretty basic question.
The value option of the form helper needs to be a string, inputs don't know what to do with something like an array.
Your array has this structure
$user_name = array (
'CustomerInfo' => array(
'usr_name' => 'Ted Jones'
)
);
So the string value you want is in $user_name['CustomerInfo']['usr_name']. The form helper has no way of knowing that the string you wanted to put as value was in that part of that array.
Don't know why you tried doing an array_pop before doing an index definition. Accessing values inside an array in php is quite simple, so try to do the simple approach first and go for the array_ php functions if it's something more complicated.
For future reference, if you have an array or a variable and you want to use a value inside of it, do a debug or print_r to know how to access it. And if it's a matter of what types of data an option can take, the cake docs are a very good reference.

Categories