Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array.
foreach($json['area'] as $row) {
$name = $row['name'];
$group = $row['array']['group'];
$majority = $row['array']['majority'];
$candidates = $row['array']['candidates'];
foreach ($candidates as $candidate) {
$vote = $candidate["votes"];
$candi = $candidate["name"];
$votes = array("vote" => $vote, "candidate" => $candi);
}
$array = array("name" => $name, "group" => $group, "majority" => $majority, "votes" => $votes);
$results[] = $array;
}
Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line:
$votes = array("vote" => $vote, "candidate" => $candi);
If you want to capture multiple entries in that array for each row, you need to make it a multi-dimensional array also:
$candidates = $row['array']['candidates'];
$votes = [];
foreach ($candidates as $candidate) {
$votes[] = array(
"vote" => $candidate["votes"],
"candidate" => $candidate["name"]
);
}
$array = array(
"name" => $name,
"group" => $group,
"majority" => $majority,
"votes" => $votes
);
Related
I have the below code but I'm not getting all the results from the array
foreach ($reviewers as $login_name => $common_name) {
$allowed_values = [
'' => 'All',
$login_name => $common_name,
];
}
You overwrite the entire array each time through the loop. Just add the key and value in the loop:
$allowed_values = ['' => 'All'];
foreach ($reviewers as $login_name => $common_name) {
$allowed_values[$login_name] = $common_name;
}
I have following foreach loop
$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$output1 = $idstand++;
echo "<li>product_id_$output1 = $item,</li>";
}
I want to add the output of the above loop inside following associative array
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge
)
So that the final array will look like this;
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge,
'product1_id' => 1255,
'product2_id' => 1256,
'product3_id' => 1257,
)
I tried creating following solution but its not working for me
$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$idoutput1 = $idstand++;
$paramas [] = array (
'product$idoutput1_id' => $item,
);
}
Need advice.
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...
$paramas['product' . $idoutput1 . '_id'] = $item;
I need a way to dynamically access values in a nested array using an index map. What i want to achieve is looping over an array with data and extract some values that can be in any level of the nesting and save it to a bi-dimensional array.
So far I've come up with the following code, which works quite well, but I was wondering if there is a more efficient way to do this.
<?php
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456') );
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978') );
// map of indexes of $array I need in my final result array. The levels of the nested indexes is subdivided by ":"
$map = array("code", "ship:name", "departure:port", "document:type", "document:data:number");
$result = array();
// loop array for rows of data
foreach($array as $i => $row){
// loop map for indexes
foreach($map as $index){
// extract specific nested values from $row and save them in 2-dim array $result
$result[$i][$index] = xpath_array($index, $row);
}
}
// print out result
print_r($result);
// takes path to value in $array and returns given value
function xpath_array($xpath, $array){
$tmp = array();
// path is subdivded by ":"
$elems = explode(":", $xpath);
foreach($elems as $i => $elem){
// if first (or ony) iteration take root value from array and put it in $tmp
if($i == 0){
$tmp = $array[$elem];
}else{
// other iterations (if any) dig in deeper into the nested array until last item is reached
$tmp = $tmp[$elem];
}
}
// return found item (can be value or array)
return $tmp;
}
Any suggestion?
This was quite tricky for me, i used Recursive function, first we normalize array keys to obtain key as you want like this document:type, then we normalize array to obtain all at same level :
/**
* #param array $array
* #param string|null $key
*
* #return array
*/
function normalizeKey(array $array, ?string $key = ''): array
{
$result = [];
foreach ($array as $k => $v) {
$index = !empty($key) && !\is_numeric($key) ? $key.':'.$k : $k;
if (true === \is_array($v)) {
$result[$k] = normalizeKey($v, $index);
continue;
}
$result[$index] = $v;
}
return $result;
}
/**
* #param array $item
* #param int $level
*
* #return array
*/
function normalizeStructure(array $item, int $level = 0): array
{
foreach ($item as $k => $v) {
$level = isset($v['code']) ? 0 : $level;
if (true === \is_array($v) && 0 === $level) {
$item[$k] = normalizeStructure($v, ++$level);
continue;
}
if (true === \is_array($v) && 0 < $level) {
$item = \array_merge($item, normalizeStructure($v, ++$level));
unset($item[$k]);
continue;
}
}
return $item;
}
$data = normalizeStructure(normalizeKey($array));
I edited your data set to add more nests:
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456'));
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978', 'check' => ['number' => '998', 'code' => 'itsWell', 'inception' => ['border' => 'finalInception']]));
With these data, you should finally receive this result:
/*
Array
(
[0] => Array
(
[code] => ABC123
[ship:name] => Fortune
[ship:code] => FA
[departure:port] => Amsterdam
[departure:code] => AMS
[document:type] => Passport
[document:data:valid] => 2022-03-18
[document:data:number] => AX123456
)
[1] => Array
(
[code] => QWERT67
[ship:name] => Dream
[ship:code] => DR
[departure:port] => Barcelona
[departure:code] => BRC
[document:type] => Passport
[document:data:valid] => 2024-12-09
[document:data:number] => DF908978
[document:data:check:number] => 998
[document:data:check:code] => itsWell
[document:data:check:inception:border] => finalInception
)
)
*/
Recursivity seems to be like Inception, everything is nested and you can lose your mind in 😆, mine was already lost in.
How to return all array values inside foreach loop. Return is working fine and no error but is only one record. If i have 10 records in database, It supposed to be all records. What did i missed this code? thanks for your help.
PHP
function myfunction(){
$query ="SELECT * from tbl_data";
$stmt = $this->getConnection()->prepare($query);
$stmt->execute();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array = array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]);
}
return $array;
}
You are currently actually just overwriting $array, you need to push the new data to it instead.
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array[] = [
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
];
}
return $myArray;
You are assigning $array on every iteration, overwriting the previous value.
Maybe you want to create an array of arrays:
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($array, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $array;
You are only getting one value returned because you are overwriting the value of the array each time.
You need to push the new values each loop iteration.
$myArray = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($myArray, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $myArray;
This will return an array of arrays.
I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}