I have this multidimensional array in php:
$products = array(array(
"name" => "Hannah",
"id" => "eg01",
"price" => 120
),
array(
"name" => "Natasha",
"id" => "eg02",
"price" => 125
));
How do I push new data in the array and save it?
I tried this code:
array_push($products, $name, $id, $price);
but it only replaces the new one every time I click the push button.
I wanted it to be saved every time i push.
Either you can use array_push() method for inserting records in an array or we can append data like this
$products[] = ['key'=>'value'];
Your array is made of sub arrays with named keys, you need to construct your inner array first.
array_push($products,array('name'=>$name,'id'=>$id,'price'=>$price));
or for verbosity
$item = array(
'name' => $name,
'id' => $id,
'price' => $price
);
array_push( $products, $item );
you may also see this syntax
$products[] = array('name'=>$name,'id'=>$id,'price'=>$price);
in which you can optionally specify a key if needed between the [] notation
Related
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);
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!
I would like to add an array to within an existing array.
I am tryin to use array_push which works as long as i dont try to assign a key to the array (if i try to add a key i get a syntax error... :-()
This is my initial array:
$ResultArray = array(
"TransactionDate" => "$TransactionDate",
"tx"=>array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
),
"1"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
)
)
);
i would then like to add:
$ArrayTOAdd = array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" =>
"$PaymentConfirmedCount"
)
);
if I try:
array_push($ResultArray->tx, $ArrayTOAdd);
BUT this does not work and results in a warning of "array_push() [function.array-push]: First argument should be an array"
if i try this :
array_push($ResultArray, $ArrayTOAdd);
it just adds the array but not to $ResultArray->tx
Any suggestions would be greatly welcomed!
You have to access the element in the array with $ResultArray["tx"] and not $ResultArray->tx. The second one is for the access to members in a php class. So an
array_push($ResultArray["tx"], $ArrayTOAdd);
should work.
How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);
What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.