I get() an multidimensional array and store it inside the $products variable.
I need to Make a copy of that array to create it into a new Webshop because the export provided by the API does not work so I have created this script to copy the data:
foreach ($products as $id => $product) {
$copy = $products[$id];
$createdProducts = $apiSkylux->products->create(
array(
'id' => $copy['id'],
'createdAt' => $copy['createdAt'],
'updatedAt' => $copy['updatedAt'],
'isVisible' => $copy['isVisible'],
'visibility' => $copy['visibility'],
'data01' => $copy['data01'],
'data02' => $copy['data02'],
'data03' => $copy['data03'],
'url' => $copy['url'],
'title' => $copy['title'],
'fulltitle' => $copy['fulltitle'],
'description' => $copy['description'],
'content' => $copy['content'],
'set' => $copy['set'],
'brand' => $copy['brand'],
'categories' => $copy['categories'],
'deliverydate' => $copy['deliverydate'],
'image' => $copy['image'],
'images' => $copy['images'],
'relations' => $copy['relations'],
'reviews' => $copy['reviews'],
'type' => $copy['type'],
'attributes' => $copy['attributes'],
'supplier' => $copy['supplier'],
'tags' => $copy['tags'],
'variants' => $copy['variants'],
'movements' => $copy['movements'],
)
);
}
The copy is working. But i thought #2016 and all, can't this be achieved with less lines of code?
This is what I receive with var_dump of the first array:
var_dump($products[0]);
exit;
//result
array(28) {
["id"]=>
int(26136946)
//rest of array
So I can see the array has a number (28) , what does this represent?
I've tried several attempts, closest attempt was :
$copy = $products[$id];
$createProducts = $products;
$createdProducts = $apiSkylux->products->create($createProducts);
But then I also got an error : Invalid data input
Can I copy the data from the array easier then the method I am currently using?
array(
'id' => $copy['id'],
...
)
This can be reduced to simply:
$copy
Yes, reassigning every single key into a new array is the same as using the original array in the first place.
foreach($products as $id => $product){
$copy = $products[$id];
This can be reduced to:
foreach ($products as $product){
$copy = $product;
Obviously you could leave out $copy entirely and just use $product.
Bottom line:
foreach ($products as $product) {
$createdProducts = $apiSkylux->products->create($product);
}
What you do with $createdProducts I don't know; you don't seem to be doing anything with it inside the loop, so at best it'll hold the last product after the loop, so is probably superfluous.
Probably you could do:
array_map([$apiSkylux->products, 'create'], $products);
or
$createdProducts = array_map([$apiSkylux->products, 'create'], $products);
depending on whether you need the return values or not.
So I can see the array has a number (28) , what does this represent?
It means it's an array with 28 elements in it.
This doesn't make any sense. Simply use the $product variable within the loop. Done!
Related
I have the following array built:
$arr['ticket']['custom_fields'][] = array('id'=>$key,'value'=>$value);
I want to dump the contents of that array inside the following section, rather than stating each index such as $arr['ticket']['custom_fields'][0]. When I try a for each loop, it fails using var_dump or even var_export? Any ideas on how I might do this?
$create = json_encode(array('ticket' => array('subject' => $arr['z_subject'],
'comment' => array( "body"=> $arr['z_description']), 'requester' =>
array('name' => $arr['z_name'], 'email' => $arr['z_requester']),
'custom_fields' => array(**$arr['ticket']['custom_fields'][]**))));
I want to remove an item from an array. I can write this:
$item = array(
'id' => 1
'name' => 'name'
);
$item2 = $item;
unset($item2['id']);
$names[] = $item2;
but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:
$item = array(
'id' => 1
'name' => 'name'
);
$names[] = array_ignore_index('id', $item);
From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:
For example IF you have :
$items = array(
array(
//this is your item 1
'id' => 1,
'name' => 'name1'
),
array(
//this is item 2
'id' => 2,
'name' => 'name2'
)
);
and you want to retrieve the names in the names array.
You can just do:
$names = array_column($items, 'name');
It will return:
Array
(
[0] => "name1"
[1] => "name2"
)
Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.
The shortest out of the box solution is to create a diff of the array keys:
$names[] = array_diff_key($item, array_flip(['id']));
See http://php.net/array_diff_key.
function array_ignore_index($id,$item){ ///function
unset($item[$id]);
return $item;
}
$a=array('id'=>1,
'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present
Here is the code for required operation..
You can use unset array column
Code is
unset($item['id']);
To test it
print_r($item);
what is use of multidimensional array(2D,3D or what is the limit in multidimensional array) and foreach()?
foreach() is use for printing values inside array?
In case of multidimensional array why nested loop is important?
Errors:
Notice: Array to string conversion in C:\xampp\htdocs\example\basic\foreach2.php on line 9
Arrayarray(3) { [0]=> int(4) [1]=> int(5) [2]=> int(7) }
Notice: Array to string conversion in C:\xampp\htdocs\example\basic\foreach2.php on line 11
$items = array(1,2,3,
array(4,5,7
),
8,54,4,5,5);
foreach($items as $key => $value)
{
echo $value;
var_dump($value);
echo $key ."pair match".$value . "<br>";
}
HOW do I access this array?
$a_services = array(
'user-login' => array(
'operations' => array(
'retrieve' => array(
'help' => 'Retrieves a user',
'callback' => 'android',
'file' => array('type' => 'inc', 'module' => 'android_services'),
'access callback' => 'services',
'args' => array(
array(
'name' => 'phone_no',
'type' => 'string',
'description' => 'The uid ',
'source' => array('path' => 0),
'optional' => FALSE,
),
),
),
),
),
);
print_r($a_services['$android_services ']['user-login']['operations']['retrieve']['callback']);
print_r($a_services['$android_services ']['user-login']['operations']['retrieve']['callback']['args']['name']);
Error 1. Notice: Array to string conversion
2. Undefined index: $android_services
3. How to print with help of foreach
4. above array is 4 dimensional??????
To loop through this kind of array you need some sort of recursiveness.
I usually call a function inside the for each. the function tests whether the current element is an array. If so the functions call itself. If not the function does whatever (echo the value in your example).
Something like:
foreach($a_services as $key => $value) {
do_your_thing($value);
}
function do_your_thing($recvalue)
{
if (is_array($recvalue))
{
foreach($recvalue as $key => $value)
{
do_your_thing($value);
}
}
else
{
echo $recvalue;
}
return $recvalue;
}
You can define multidimension arrays (arrays including oher arrays) in PHP.
For example you have 2 different lists, one for grocery shopping, one for daily task.
$lists = array(
'grocery' => array('banana', 'apple'),
'tasks' => array('go to work', 'wash dishes'),
);
If you want to check all levels of arrays, you should use nested loops. For example you can use foreach, it will iterate over arrays first level.
foreach($lists as $list)
return $list; // returns grocery[] and tasks[]
As you see this loop returning other loop. So if you need to list all grocery[] array items, you need iterate again in this array.
foreach($lists as $list)
foreach($list as $k => $l)
if($k == 'grocery')
echo $l; // echos "banana","apple"
Nested loops are important (and necessary) to reach multidimensional arrays contents especially if you don't know structure of the array. These loops will find all array items for you. But if you know structure, you can directly use $lists['grocery'] to reach grocery array or $lists['grocery'][0] to reach first element of your grocery list.
I have an application using PHP CodeIgniter's Cart library. And I need this output, to send info to google analytics:
$itemsga = array(
array('sku'=>'SDFSDF', 'name'=>'Shoes', 'category'=>'Footwear', 'price'=>'100', 'quantity'=>'1'),
array('sku'=>'123DSW', 'name'=>'Sandles', 'category'=>'Footwear', 'price'=>'87', 'quantity'=>'1'),
array('sku'=>'UHDF93', 'name'=>'Socks', 'category'=>'Footwear', 'price'=>'5.99', 'quantity'=>'2')
);
To achieve that, I created this code:
$itemsga = array(
foreach ($this->cart->contents() as $items){
array(
'sku' => $items['id'],
'name' => $items['name'],
'price' => $items['price'],
'quantity' => $items['qty'],
),
}//endforeach
);
For some reason I'm getting a white screen. No error displayed but my array is not being built.
I know this might be a stupid question, but I got stuck. Can someone help me?
Cheers!
Change your code to:-
$itemsga = array(); // define array variable
foreach ($this->cart->contents() as $items){
$itemsga[] = array(
'sku' => $items['id'],
'name' => $items['name'],
'price' => $items['price'],
'quantity' => $items['qty'],
); // done indexing and add complete array to each index.
}//endforeach
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.