Creating array using loop - php

I need to create array using loop, How to do it
Here is my array
$data = array(
value1 => 1,
value2 => 32,
value3 => 25
);
for (i=o,i<2,i++) {
}
If i value is 2 my array should be like
$arrays = (array(data,data));
If i value is 3my array should be like
$arrays=(array(data,data,data));
Help me to create array like this
If i i value is 2 means ouput should be like
result =(array(value1 => 1,value2 => 32,value3 => 25),(value1 => 1,value2 => 32,value3 => 25));
);

Do you mean this:
<?php
$data = array(
'value1' => 1,
'value2' => 32,
'value3' => 25
);
$finalArr = [];
for ($i=0;$i<2;$i++) {
$finalArr[] = $data;
}
print_r($finalArr);
Output:
Array
(
[0] => Array
(
[value1] => 1
[value2] => 32
[value3] => 25
)
[1] => Array
(
[value1] => 1
[value2] => 32
[value3] => 25
)
)
Your Eval sample

below code give output as
<?php
$data = array(
'value1' => 1,
'value2' => 32,
'value3' => 25
);
$finalArr = [];
for ($i=1;$i<=3;$i++) {
$finalArr['value'.$i] = $data['value'.$i];
}
print_r($finalArr);
?>
Array
(
[value1] => 1
[value2] => 32
[value3] => 25
)
if you dont need value1 in side array ie [value1]=>1
then remove 'value'.$i from $finalArr['value'.$i]
if you can change the value of $ according to the number of your array

So from what I understand, you want an array with a number of values...
$size = 5; # Size of the array
$array = array(); # The empty array to begin with
$value = array('value1' => '1', 'value2' => '32', 'value3' => '25');
// Create our array with a for loop
for($i=1; $i<=$size; $i++)
array_push($array, $value);
The var_dump of the array would be:
array(5) {
[0]=>
array(3) {
["value1"]=>
string(1) "1"
["value2"]=>
string(2) "32"
["value3"]=>
string(2) "25"
}
[1]=>
array(3) {
["value1"]=>
string(1) "1"
["value2"]=>
string(2) "32"
["value3"]=>
string(2) "25"
}
[2]=>
array(3) {
["value1"]=>
string(1) "1"
["value2"]=>
string(2) "32"
["value3"]=>
string(2) "25"
}
[3]=>
array(3) {
["value1"]=>
string(1) "1"
["value2"]=>
string(2) "32"
["value3"]=>
string(2) "25"
}
[4]=>
array(3) {
["value1"]=>
string(1) "1"
["value2"]=>
string(2) "32"
["value3"]=>
string(2) "25"
}
}

Related

How could I get each value of an array?

I have an array like this :
array(3) {
["data"]=> array(1) {
["mesq_G3SC"]=> array(1) {
["data"]=> object(stdClass)#30 (19) {
["cart_id"]=> string(13) "mesq_G3SC"
["qty"]=> string(4) "2.00"
["price"]=> string(5) "11400"
["product_id"]=> string(1) "6"
["member_id"]=> string(1) "5"
["session_id"]=> string(32) "4dedde2a2eb12b25e940b7051a5f65a1"
["date_added"]=> string(19) "2016-09-28 10:39:06"
["date_modified"]=> string(19) "2016-09-28 10:39:06"
["status"]=> string(7) "pending"
["category_id"]=> string(1) "2"
["location"]=> string(9) "England"
["square"]=> string(3) "300"
["stock"]=> string(3) "260"
["folder_name"]=> string(23) "assets/uploads/products"
["photo1"]=> string(11) "photo1.jpg"
["photo2"]=> string(11) "pc.jpg"
["category_name"]=> string(6) "PC"
["is_published"]=> string(1) "1"
["modified_by"]=> NULL
}
}
}
["total_item"]=> int(1)
["total_price"]=> string(8) "11400.00"
}
I would to get each value of that array with foreach but I got error
Trying to get property of non-object...
I developed this with Codeigniter and this is my foreach:
foreach ($data as $row) {
echo $row->product_id;
}
This is what I get if I do print_r($row) :
Array ( [mesq_G3SC] => Array ( [data] => stdClass Object ( [cart_id] => mesq_G3SC [qty] => 2.00 [price] => 11400 [product_id] => 6 [member_id] => 5 [session_id] => 4dedde2a2eb12b25e940b7051a5f65a1 [date_added] => 2016-09-28 10:39:06 [date_modified] => 2016-09-28 10:39:06 [status] => pending [category_id] => 2 [lokasi_lahan] => England [square] => 300 [stock] => 260 [folder_name] => assets/uploads/products [photo1] => photo1.jpg [photo2] => photo2.jpg [category_name] => PC [is_published] => 1 [modified_by] => ) ) ) 1 11400.00
Anyone knows how to get each value of that array?
I re-created your multidimensional array, if you want to get the deepest values, here it is:
$deepest_values = array();
foreach($arr_ as $first_level_key => $first_level_value) {
if(is_array($first_level_value)) {
foreach($first_level_value as $second_level_key => $second_level_value) {
if(is_array($second_level_value)) {
foreach($second_level_value as $third_level_key => $third_level_value) {
if(is_array($third_level_value)) {
foreach($third_level_value as $fourth_level_key => $fourth_level_value) {
$deepest_values[$fourth_level_key] = $fourth_level_value;
}
}
}
}
}
}
}
echo '<pre>';
print_r($deepest_values);
echo '</pre>';
if mesq_G3SC is the key you want to iterate over - i suggest you do the following
$obj = new stdClass();
$obj->cart_id = "mesq_G3SC";
$obj->qty = "2.00";
$obj->price = "11400";
$obj->product_id = "6";
$obj->member_id = "5";
$obj->session_id = "4dedde2a2eb12b25e940b7051a5f65a1";
$obj->date_added = "2016-09-28 10:39:06";
$obj->date_modified = "2016-09-28 10:39:06";
$obj->status = "pending";
$obj->category_id = "2";
$obj->location = "England";
$obj->square = "300";
$obj->stock = "260";
$obj->folder_name = "assets/uploads/products";
$obj->photo1 = "photo1.jpg";
$obj->photo2 = "pc.jpg";
$obj->category_name = "PC";
$obj->is_published = "1";
$obj->modified_by = NULL;
$data = array(
"mesq_G3SC"=> array(
"data"=> $obj
),
"total_item" => 1,
"total_price" => "11400.00"
);
foreach($data['mesq_G3SC'] AS $key => $obj)
{
echo $key;
print_r($obj);
}
Update: i simulated your array - and it works like a charm - there is something wrong with the keys - instead of var_dump try to print_r your data array and show us the output pls

Replacing inner keys from multidimensional array in PHP

Having the following array:
array(4) {
[0]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(37) "some data"
}
[1]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(68) "some other data"
}
[2]=>
array(2) {
[0]=>
string(3) "144"
[1]=>
string(38) "some other data"
}
[3]=>
array(2) {
[0]=>
string(3) "233"
[1]=>
string(42) "some other data"
}
}
I want to replace the values 233 and 144 (the key 0 from the inner array) by some random HEX color. The ones with the same keys (233) for example, has to have the same HEX color (FFF000 for example in the desired solution above).
This is the function I use to generate random HEX colors:
function randHEXcolor() {
return sprintf('%06X', mt_rand(0, 0xFFFFFF));
}
My desired output should be:
array(4) {
[0]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(37) "some data"
}
[1]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(68) "some other data"
}
[2]=>
array(2) {
[0]=>
string(6) "111333"
[1]=>
string(38) "some other data"
}
[3]=>
array(2) {
[0]=>
string(6) "FFF000"
[1]=>
string(42) "some other data"
}
}
How can I archieve this?
Thanks in advance.
foreach ($array as &$item) {
if (!isset($temp[$item[0]]) {
$temp[$item[0]] = randHEXcolor();
}
$item[0] = $temp[$item[0]];
}
If you want all values to be translated to the same random color, you'll have to save those colors:
$colors_translation = array();
foreach ($array as &$item) {
$color = $item[ 0 ];
$translate = $colors_translation[ $color ];
if (empty($translate)) {
$colors_translations[ $color ] = $translate = randHEXcolor();
}
$item[ 0 ] = $translate;
}
The solution using in_array and isset functions:
$keys = [];
foreach ($arr as &$v) { // $arr is your initial array
if (in_array($v[0], ['233', '144'])) {
if (!isset($keys[$v[0]])) $keys[$v[0]] = sprintf('%06X', mt_rand(0, 0xFFFFFF));
$v[0] = $keys[$v[0]];
}
}
print_r($arr);
The output:
Array
(
[0] => Array
(
[0] => 65A4BB
[1] => some data
)
[1] => Array
(
[0] => 65A4BB
[1] => some data
)
[2] => Array
(
[0] => DDB588
[1] => some data
)
[3] => Array
(
[0] => 65A4BB
[1] => some data
)
)
This code will create a color map as the array is traversed. Pre-populate $colorMap if you want pre-defined color translations.
<?php
$array = array(
0 => array(
0 => "233",
1 => "some data"
),
1 => array(
0 => "233",
1 => "some data"
),
2 => array(
0 => "144",
1 => "some data"
),
3 => array(
0 => "233",
1 => "some data"
),
);
$colorMap = array();
foreach ($array as &$inner) {
if (!array_key_exists($inner[0],$colorMap)) {
$newColor = randHEXcolor();
$colorMap[$inner[0]] = $newColor;
$inner[0] = $newColor;
} else {
$inner[0] = $colorMap[$inner[0]];
}
}
function randHEXcolor() {
return sprintf('%06X', mt_rand(0, 0xFFFFFF));
}
print_r($array);
print_r($colorMap);
Array
(
[0] => Array
(
[0] => F1519A
[1] => some data
)
[1] => Array
(
[0] => F1519A
[1] => some data
)
[2] => Array
(
[0] => 2F7D00
[1] => some data
)
[3] => Array
(
[0] => F1519A
[1] => some data
)
)
Array
(
[233] => F1519A
[144] => 2F7D00
)
Try:
<?php
$array = array(
0 => array(
0 => "233",
1 => "some data"
),
1 => array(
0 => "233",
1 => "some data"
),
2 => array(
0 => "144",
1 => "some data"
),
3 => array(
0 => "233",
1 => "some data"
),
);
function randHEXcolor() {
return sprintf('%06X', mt_rand(0, 0xFFFFFF));
}
$firstHex = randHEXcolor();
$secondHex = randHEXcolor();
foreach($array as $arrayIndex => &$arrayValue){
if($arrayValue[0] == "144"){
$arrayValue[0] = $firstHex;
}
if($arrayValue[0] == "233"){
$arrayValue[0] = $secondHex;
}
}
output:
array(4) {
[0]=>
array(2) {
[0]=>
string(6) "AB8248"
[1]=>
string(9) "some data"
}
[1]=>
array(2) {
[0]=>
string(6) "AB8248"
[1]=>
string(9) "some data"
}
[2]=>
array(2) {
[0]=>
string(6) "22AF8B"
[1]=>
string(9) "some data"
}
[3]=>
&array(2) {
[0]=>
string(6) "AB8248"
[1]=>
string(9) "some data"
}
}

Add xml child to array php

I'm trying to add each <outfit>Subnodes</outfit> subnodes to an array using php.
My actual code:
public static function get_outfits($username) {
$files = self::user_files($username);
$data = self::request($files['outfits']);
$data = #simplexml_load_string($data);
if ( $data && count(#$data->xpath('//outfits/outfit')) > 0 ) {
foreach(#$data->xpath('//outfits/outfit/*') as $items) {
$response['outfits']['items'][] = array(
"url" => (string)$items['url'],
"c" => (string)$items['c'],
"c2" => (string)$items['c2'],
"displayName" => (string)$items['displayName'],
"z" => (string)$items['z'],
"id" => (string)$items['id'],
"isUgc" => (string)$items['isUgc']
);
}
}
return (isset($response) ? $response : false);
}
The xml document looks like the following: http://outfits.zwinky.com/users/220/287/_perverted/outfits.xml
Sadly the code is saving every existing child into one array. But I'm trying to create an array index for each <outfit></outfit> node which should contain the child elements.
For example:
Array[0] = Everything between the first <outfit><outfit>
Array[1] = Everything between the second <outfit><outfit>
Does anyone have an idea, how to create this?
You need two loops, one for the outfit elements and one for the inner item elements. On the other side, you don't need the condition, because iterating an empty array/node list works fine.
$outfits = new SimpleXmlElement($xml);
$result = [];
foreach ($outfits->xpath('outfit') as $outfit) {
$items = [];
foreach ($outfit->xpath('*') as $item) {
$items[$item->getName()] = [
"url" => (string)$item['url'],
"c" => (string)$item['c'],
"c2" => (string)$item['c2'],
"displayName" => (string)$item['displayName'],
"z" => (string)$item['z'],
"id" => (string)$item['id'],
"isUgc" => (string)$item['isUgc']
];
}
$result[] = [
'name' => (string)$outfit['name'],
'items' => $items
];
}
var_dump($result);
Output:
array(14) {
[0]=>
array(2) {
["name"]=>
string(6) "babe13"
["items"]=>
array(14) {
["head"]=>
array(7) {
["url"]=>
string(51) "http://.../assets/babe/heads/01/head1"
["c"]=>
string(8) "0xF4C4A4"
["c2"]=>
string(8) "0xffffff"
["displayName"]=>
string(0) ""
["z"]=>
string(5) "33000"
["id"]=>
string(0) ""
["isUgc"]=>
string(0) ""
}
["face"]=>
array(7) {
["url"]=>
string(50) "http://.../assets/babe/faces/01/grl1"
["c"]=>
string(3) "0x0"
["c2"]=>
string(8) "0xFF0000"
["displayName"]=>
string(5) "girl1"
["z"]=>
string(5) "34000"
["id"]=>
string(8) "20014794"
["isUgc"]=>
string(0) ""
}
...
If this is the output you want :-
Array
(
[0] => Array
(
[url] => http://assets.zwinky.com/assets/babe/heads/01/head1
[c] => 0xF4C4A4
[c2] => 0xffffff
[displayName] =>
[z] => 33000
[id] =>
[isUgc] =>
)
[1] => Array
(
[url] => http://assets.zwinky.com/assets/babe/faces/01/grl1
[c] => 0x0
[c2] => 0xFF0000
[displayName] => girl1
[z] => 34000
[id] => 20014794
[isUgc] =>
)
[2] => Array
(
[url] => http://assets.zwinky.com/assets/babe/midsections/01/ms1
[c] => 0xBCE4FE
[c2] =>
[displayName] =>
[z] => 9000
[id] =>
[isUgc] =>
)
... etc etc
Then all you need to do is change the code to this
public static function get_outfits($username) {
$files = self::user_files($username);
$data = self::request($files['outfits']);
$data = #simplexml_load_string($data);
if ( $data && count(#$data->xpath('//outfits/outfit')) > 0 ) {
foreach(#$data->xpath('//outfits/outfit/*') as $items) {
// $response['outfits']['items'][] = array(
$response[] = array(
"url" => (string)$items['url'],
"c" => (string)$items['c'],
"c2" => (string)$items['c2'],
"displayName" => (string)$items['displayName'],
"z" => (string)$items['z'],
"id" => (string)$items['id'],
"isUgc" => (string)$items['isUgc']
);
}
}
return (isset($response) ? $response : false);
}

split array based on value

I have array like this:
array(4) {
[0]=>
array(2) {
[0]=>
string(2) "L2"
[1]=>
string(5) "Apple"
}
[1]=>
array(2) {
[0]=>
string(2) "L3"
[1]=>
string(3) "Cat"
}
[2]=>
array(2) {
[0]=>
string(2) "L2"
[1]=>
string(6) "Orange"
}
[3]=>
array(2) {
[0]=>
string(2) "L3"
[1]=>
string(3) "Dog"
}
}
I want make a conclusion:
a) what are content of L2?
b) what are content of L3?
So I make array $L2 and $L3.
But, I have no idea how to push some array in one array.
I already try this one:
for($j=0; $j<count($arrL); $j++){
if($arrL[$j][0] == "L2"){
$L2[] = $arrL[$j][1];
}else if($arrL[$j][0] == "L3"){
$L3[] = $arrL[$j][1];
}
}
But, the result is:
array(0) {
}
you have any idea?
Your code is just fine. If I understand what do you want correctly then perhaps this might help you out. This is the code that I am using:
$arrL = array(
0 => array(
0 => "L2", 1 => "Apple"
),
1 => array(
0 => "L3", 1 => "Cat"
),
2 => array(
0 => "L2", 1 => "Orange"
),
3 => array(
0 => "L3", 1 => "Dog"
)
);
for($j=0; $j<count($arrL); $j++){
if($arrL[$j][0] == "L2"){
$L2[] = $arrL[$j][1];
}else if($arrL[$j][0] == "L3"){
$L3[] = $arrL[$j][1];
}
}
echo 'My L2 Array: ';
print_r($L2);
echo 'My L3 Array: ';
print_r($L3);
And here is the output:
My L2 Array: Array ( [0] => Apple [1] => Orange ) My L3 Array: Array ( [0] => Cat [1] => Dog )

php switch array key with subelement key

I would like to switch the main keys(0,1,2) of an array with a subelement key(user_id).
For example, from this array:
array(3) {
[0]=>
array(3) {
["num_products_user_by_ref"]=>
string(1) "1"
["user_id"]=>
string(2) "77"
["reference"]=>
string(3) "E49"
}
[1]=>
array(3) {
["num_products_user_by_ref"]=>
string(1) "9"
["user_id"]=>
string(3) "526"
["reference"]=>
string(3) "E49"
}
[2]=>
array(3) {
["num_products_user_by_ref"]=>
string(2) "38"
["user_id"]=>
string(3) "346"
["reference"]=>
string(3) "E49"
}
}
I need :
array(952) {
[77]=>
array(2) {
["num_products_user_by_ref"]=>
string(1) "1"
["reference"]=>
string(3) "E49"
}
[526]=>
array(3) {
["num_products_user_by_ref"]=>
string(1) "9"
["reference"]=>
string(3) "E49"
}
[346]=>
array(3) {
["num_products_user_by_ref"]=>
string(2) "38"
["reference"]=>
string(3) "E49"
}
Every user_id could contains more than 1 pair num_products_user_by_ref/reference.
I remember that there is a function to achieve this (ksort?) associated to a custom function to implement.
$out = array();
foreach ($arr as $key => $value){
$out[$value['user_id']]["num_products_user_by_ref"] = $value["num_products_user_by_ref"];
$out[$value['user_id']]["reference"] = $value["reference"];
}
print_r($out);
Your question showed a structure that doesn't seem to fit with your comment "Every user_id could contains more than 1 pair num_products_user_by_ref/reference." So, here's another version that allows for that possibility:
$out = array();
foreach ($arr as $key => $value){
$entry = array("num_products_user_by_ref" => $value["num_products_user_by_ref"],
"reference" => $value["reference"]);
$out[$value['user_id']][] = $entry;
}
Output:
Array
(
[77] => Array
(
[0] => Array
(
[num_products_user_by_ref] => 1
[reference] => E49
)
[1] => Array
(
[num_products_user_by_ref] => 5
[reference] => E49
)
)
[526] => Array
(
[0] => Array
(
[num_products_user_by_ref] => 9
[reference] => E49
)
)
[346] => Array
(
[0] => Array
(
[num_products_user_by_ref] => 38
[reference] => E49
)
)
)
Here's another version for those who don't like traditional loops:
$out = array();
array_walk($arr, function($e, $k) use(&$out){
$entry = array("num_products_user_by_ref" => $e["num_products_user_by_ref"],
"reference" => $e["reference"]);
$out[$e['user_id']][] = $entry;
});

Categories