Reputation: 3044
In my PHP, I have the following Array..
$json = array(
"ack" => "success",
"totalPages" => $total_pages,
"currentPage" => $pageno,
"results" => array()
);
I go through an array, increment a counter. Where I would return my encoded json, I add the counter into the $json
array.
echo $counter //returns the number
array_push($json['count'], $counter) //returns null
How can I push the $counter into the 'count' object?
Upvotes: 1
Views: 43
Reputation: 549
I'm assuming that $counter
would be an integer variable, instead of an array. array_push()
takes an array for the first parameter, and the additional values to add to that array.
In your case, it looks like you're wanting to set the array's key for count
to the variable $counter
, which you can do like so:
$json = array(
'ack' => 'success',
'totalPages' => $total_pages,
'currentPage' => $pageno,
'results' => array(),
'count' => 0,
);
$json['count'] = $counter;
Edit:
Additionally, if you're setting the variable above for your response, and you're not doing any further code changes, you can just declare your $json
array with the $counter
variable, similar to how you have for totalPages
and currentPage
, and for completeness:
$json = array(
'ack' => 'success',
'totalPages' => $total_pages,
'currentPage' => $pageno,
'results' => array(),
'count' => $counter, // Set the $counter variable here, straight away!
);
Upvotes: 2
Reputation: 4211
no need array_push for this situation, you should do as follows
$json = array(
"ack" => "success",
"totalPages" => $total_pages,
"currentPage" => $pageno,
"results" => array()
);
$json['count']=$counter;
print_r($json); //print array for humans and see
if you use array_push in other scenarios u can use as such
for example ,
$array[]="item";
$array=[];
$array[]="foo";
$array[]="bar";
print_r($array); //["foo","bar"]
Upvotes: 0
Reputation: 6601
To update (or set) an array key you would not use array_push()
, but simply:
$json['count'] = $counter;
Upvotes: 2